策略模式
回到目录
简介
UML类图
代码示例
#include <iostream>
using namespace std;
class Strategy
{
public:
virtual void Algorithm() = 0;
};
class StrategyA : public Strategy
{
public:
virtual void Algorithm() {
std::cout << "StrategyA" << std::endl;
}
};
class StrategyB : public Strategy
{
public:
virtual void Algorithm() {
std::cout << "StrategyB" << std::endl;
}
};
class Context
{
public:
Context(Strategy *pStrategy) {
m_pStrategy = pStrategy;
}
~Context() { };
void Operation() {
if (m_pStrategy != NULL) {
m_pStrategy->Algorithm();
}
}
private:
Strategy *m_pStrategy;
};
int main(int argc , char **argv)
{
Context* pContext = new Context(new StrategyA());
pContext->Operation();
delete pContext;
pContext = new Context(new StrategyB());
pContext->Operation();
return 0;
}