2策略模式

策略模式

//策略类
class Strategy
{
public:
virtual void DoSomething() = 0;
};

class MethodA : public Strategy
{
public:
void DoSomething()
{
cout<<"this is MethodA."<<endl;
}
};

class MethodB : public Strategy
{
public:
void DoSomething()
{
cout<<"this is MethodB."<<endl;
}
};

class MethodC : public Strategy
{
public:
void DoSomething()
{
cout<<"this is MethodC."<<endl;
}
};

//上下文类,根据得到的对象匹配对应的策略类
class Context
{
public:
Context(Strategy *pStrategy) : m_pStrategy(pStrategy) //构造函数,给m_pStrategy赋值为对应的策略类指针
{
}
void Execute() //封装了对应对象的调用
{
m_pStrategy->DoSomething();
}
private:
Strategy *m_pStrategy;
};


int main()
{
//创建具体的策略对象
Strategy *pStrategy = new MethodA;
//创建调用策略的对象
Context *pContext = new Context(pStrategy);
//调用策略的方法
pContext->Execute();//打印 this is MethodA

rerurn 0;
}