策略模式
#include <iostream> #include <memory> class Strategy { public: virtual void show() = 0; }; class Context { public: void setStrategy(std::shared_ptr<Strategy> s) { s_ = s; } void show() { std::cout << "In Context show()." << std::endl; if(s_) { s_->show(); } } private: std::shared_ptr<Strategy> s_ = nullptr; }; class ConcreteStrategy1 : public Strategy { public: void show() override { std::cout << "In ConcreteStrategy1 show()." << std::endl; } }; class ConcreteStrategy2 : public Strategy { public: void show() override { std::cout << "In ConcreteStrategy2 show()." << std::endl; } }; int main(int argc, char *argv[]) { std::shared_ptr<Strategy> s1 = std::make_shared<ConcreteStrategy1>(); std::shared_ptr<Strategy> s2 = std::make_shared<ConcreteStrategy2>(); std::unique_ptr<Context> c = std::make_unique<Context>(); c->show(); c->setStrategy(s1); c->show(); c->setStrategy(s2); c->show(); return 1; }