模板方法模式
#include <iostream> #include <memory> class AbstractClass { public: void show() { op1(); op2(); op3(); hook(); } protected: void op1() { std::cout << "In AbstractClass op1()." << std::endl; } virtual void op2() = 0; void op3() { std::cout << "In AbstractClass op3()." << std::endl; } virtual void hook() {}; }; class ConcreteClass1 : public AbstractClass { protected: void op2() override { std::cout << "In ConcreteClass1 op2()." << std::endl; } }; class ConcreteClass2 : public AbstractClass { protected: void op2() override { std::cout << "In ConcreteClass2 op2()." << std::endl; } virtual void hook() override { std::cout << "In ConcreteClass2 hook()." << std::endl; } }; int main(int argc, char *argv[]) { std::shared_ptr<ConcreteClass1> cc1 = std::make_shared<ConcreteClass1>(); std::shared_ptr<ConcreteClass2> cc2 = std::make_shared<ConcreteClass2>(); cc1->show(); cc2->show(); return 1; }