#include <iostream> #include <string> using namespace std; class Stratergy { public: virtual void AlgoInterface() = 0; //注意,基类的虚函数需要有实现,否则会出现Link2001错误;也可以定义为纯虚函数来解决. }; class ConcreteStragergyA : public Stratergy { public: void AlgoInterface(); }; class ConcreteStragergyB : public Stratergy { public: void AlgoInterface(); }; class ConcreteStragergyC : public Stratergy { public: void AlgoInterface(); }; class Context { public: Context(): m_st(NULL) {} Context(string type); ~Context(); void getRlt(); private: Stratergy *m_st; }; void ConcreteStragergyA::AlgoInterface() { cout<<"This is A algo"<<endl; } void ConcreteStragergyB::AlgoInterface() { cout<<"This is B algo"<<endl; } void ConcreteStragergyC::AlgoInterface() { cout<<"This is C algo"<<endl; } Context::Context(string type) { if (type == "A") { m_st = new ConcreteStragergyA(); } else if (type == "B") { m_st = new ConcreteStragergyB(); } else { m_st = new ConcreteStragergyC(); } } Context::~Context() { if (m_st) { delete m_st; } } void Context::getRlt() { if (m_st) { m_st->AlgoInterface(); } } void main() { { Context A("A"); A.getRlt(); Context B("B"); B.getRlt(); Context C("C"); C.getRlt(); } system("pause"); }
注解:
1. 更加抽象低耦合,使用中用户只需使用Context类,不必关注每个strategy的实现。