设计模式——策略模式
将实现同一功能的多个算法封装成多个不同的类,调用时更加方便,且避免条件语句的使用。
使用Context类来决定要使用哪个算法类,使用多态实现。通过在构造Context类时指定哪个算法类来实现选择功能。
Strategy类为纯虚类,用来派生不同的算法类。
#include <iostream> using namespace std; class Strategy//纯虚类 { public: virtual ~Strategy(){} virtual void AlgorithmInterface()=0; }; class Context //上下文类 { public: Context(Strategy *pStrategy); ~Context(); void ContextInterface(); private: Strategy *m_pStrategy; //字段为指针,记得在析构函数中释放并置空 }; Context::Context(Strategy *pStrategy):m_pStrategy(pStrategy) { //上下文构造函数,把算法赋值给指针 } Context::~Context() { delete m_pStrategy; m_pStrategy=nullptr; } void Context::ContextInterface() { if(m_pStrategy != nullptr) { m_pStrategy->AlgorithmInterface();//调用对应的算法 } } class ConcreateStrategyA: public Strategy //策略A { public: virtual ~ConcreateStrategyA(){} virtual void AlgorithmInterface(); }; void ConcreateStrategyA::AlgorithmInterface() { cout<<"AlgorithmInterface AAAAA"<<endl; } class ConcreateStrategyB: public Strategy //策略B { public: virtual ~ConcreateStrategyB(){} virtual void AlgorithmInterface(); }; void ConcreateStrategyB::AlgorithmInterface() { cout<<"AlgorithmInterface BBBBB"<<endl; } int main(int argc, char *argv[]) { //创建一个基类对象指针指向派生类对象 Strategy *pStrategy = new ConcreateStrategyA(); // Context *pContext = new Context(pStrategy); pContext->ContextInterface(); delete pContext;
//delete pStrategy;//不需要,因为Context的析构函数会释放该指针 return 0; }