策略模式
策略模式最大的特点在于其低耦合性。在具体的实现中采用不同的算法,不会影响到调用者。其基本组成包括:抽象策略角色、具体策略角色和环境角色。
下面是以C++实现的示例代码:
#include <iostream> using namespace std; class IStrategy{ public: IStrategy() {} virtual ~IStrategy() {} virtual void Operate() = 0; // pure virtual function }; class Context { public: Context(IStrategy *p) { m_p = p; } ~Context() { delete m_p; } void Operate() { m_p->Operate(); } private: IStrategy *m_p; }; class BackDoor : public IStrategy { public: BackDoor() {} virtual ~BackDoor() {} virtual void Operate() { cout << "找乔国老帮忙,让吴国太给孙权施加压力。" << endl; } }; class GivenGreenLight : public IStrategy { public: GivenGreenLight() {} virtual ~GivenGreenLight() {} virtual void Operate() { cout << "求吴国太开个绿灯,放行!" << endl; } }; class BlockEnemy : public IStrategy { public: BlockEnemy() {} virtual ~BlockEnemy() {} virtual void Operate() { cout << "孙夫人断后,挡住追兵。" << endl; } }; int _tmain(int argc, _TCHAR* argv[]) { Context *pContext; cout << "----------刚刚到吴国的时候拆第一个----------" << endl; pContext = new Context(new BackDoor()); pContext->Operate(); delete pContext; cout << "\n\n\n" << endl; cout << "----------刘备乐不思蜀了,拆第二个了----------" << endl; pContext = new Context(new GivenGreenLight()); pContext->Operate(); delete pContext; cout << "\n\n\n" << endl; cout << "----------孙权的小兵追了,咋办?拆第三个----------" << endl; pContext = new Context(new BlockEnemy()); pContext->Operate(); delete pContext; return 0; }
本文参考了CBF4LIFE写的设计模式。