015 设计模式之策略模式
Posted guojun
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了015 设计模式之策略模式相关的知识,希望对你有一定的参考价值。
抽象策略角色: 策略类,通常由一个接口或者抽象类实现。
-具体策略角色:包装了相关的算法和行为。
-环境角色:持有一个策略类的引用,最终给客户端调用。
#pragma once
//策略接口(纯虚函数)
class IStrategy
{
public:
IStrategy() {}
virtual ~IStrategy(){}
virtual void Operate() = 0;
};
#pragma once
#include "IStrategy.h"
//策略1,从抽象基类继承
class OneWay :public IStrategy
{
public:
OneWay(void);
~OneWay(void);
void Operate(void);
};
#include "StdAfx.h"
#include "OneWay.h"
#include <iostream>
//构造函数
OneWay::OneWay(void)
{
}
//析构函数
OneWay::~OneWay(void)
{
}
//策略1具体实现
void OneWay::Operate(void)
{
std::cout << "找乔国老帮忙,让吴国太给孙权施加压力" << std::endl;
}
#pragma once
#include "IStrategy.h"
//策略2,从抽象基类继承
class TwoWay :public IStrategy
{
public:
TwoWay(void);
~TwoWay(void);
void Operate(void);
};
#include "stdafx.h"
#include "TwoWay.h"
#include <iostream>
#include "string"
//构造函数
TwoWay::TwoWay(void)
{
}
//析构函数
TwoWay::~TwoWay(void)
{
}
//策略2的具体实现
void TwoWay::Operate(void)
{
std::cout << "求吴国太开个绿灯,放行" << std::endl;
}
#pragma once
#include "IStrategy.h"
//策略3,从抽象基类继承
class ThreeWay :public IStrategy
{
public:
ThreeWay(void);
~ThreeWay(void);
void Operate(void);
};
#include "stdafx.h"
#include "ThreeWay.h"
#include <iostream>
//构造函数
ThreeWay::ThreeWay(void)
{
}
//析构函数
ThreeWay::~ThreeWay(void)
{
}
//策略3的具体实现
void ThreeWay::Operate()
{
std::cout << "孙夫人断后,挡住追兵" << std::endl;
}
#pragma once
#include "IStrategy.h"
//锦囊
class CContext
{
public:
//构造函数
CContext(IStrategy *pStrategy);
//析构函数
~CContext(void);
//行为
void Operate(void);
private:
IStrategy * m_pStrategy;
};
#include "stdafx.h"
#include "Bag.h"
//构造函数
CContext::CContext(IStrategy *pStrategy)
{
this->m_pStrategy = pStrategy;
}
//析构函数
CContext::~CContext()
{
delete this->m_pStrategy;
}
//行为
void CContext::Operate()
{
m_pStrategy->Operate();
}
#include "stdafx.h"
#include "Bag.h"
#include "OneWay.h"
#include "TwoWay.h"
#include "ThreeWay.h"
#include <iostream>
int _tmain(int argc, _TCHAR* argv[])
{
CContext *pContext;
std::cout << "----------刚刚到吴国的时候拆第一个----------" << std::endl;
pContext = new CContext(new OneWay());
pContext->Operate();
delete pContext;
std::cout << "----------刘备乐不思蜀了,拆第二个了----------" << std::endl;
pContext = new CContext(new TwoWay());
pContext->Operate();
delete pContext;
std::cout << "----------孙权的小兵追了,咋办?拆第三个----------" << std::endl;
pContext = new CContext(new ThreeWay());
pContext->Operate();
delete pContext;
return 0;
}
以上是关于015 设计模式之策略模式的主要内容,如果未能解决你的问题,请参考以下文章