策略模式:
定义一组算法,对不同算法进行封装,算法彼此独立;并且算法与包装类(以下代码Context类)减少了耦合
以下代码可以与工厂方法模式结合使用,在实际应用中也经常会两种模式结合使用,例如游戏里的节日活动、利用不同时间周期计算时间点等
按照UML类图,代码如下:
#include "stdafx.h"
#include <iostream>
using namespace std;
class StrategyBase
{
public:
virtual ~StrategyBase()
{
}
virtual void AlgorithmInterface()
{
cout << "StrategyBase::AlgorithmInterface" << endl;
}
};
class ConcreteStrategyA : public StrategyBase
{
public:
virtual ~ConcreteStrategyA()
{
}
virtual void AlgorithmInterface()
{
cout << "ConcreteStrategyA::AlgorithmInterface" << endl;
}
};
class ConcreteStrategyB : public StrategyBase
{
public:
virtual ~ConcreteStrategyB()
{
}
virtual void AlgorithmInterface()
{
cout << "ConcreteStrategyB::AlgorithmInterface" << endl;
}
};
class Context
{
public:
Context(StrategyBase* pConcreteStrategy)
{
m_pConcreteStrategy = pConcreteStrategy;
}
~Context()
{
if (nullptr != m_pConcreteStrategy)
{
delete m_pConcreteStrategy;
m_pConcreteStrategy = nullptr;
}
}
void Operation()
{
if (nullptr == m_pConcreteStrategy)
{
return;
}
m_pConcreteStrategy->AlgorithmInterface();
}
private:
StrategyBase* m_pConcreteStrategy;
};
int main()
{
{
StrategyBase* pStrategy = new ConcreteStrategyB;
Context objContext(pStrategy);
objContext.Operation();
}
system("pause");
return 0;
}
输出:
ConcreteStrategyB::AlgorithmInterface