protected: // 默认实现部分步骤方法 voidBaseOperation1(){ std::cout << "AbstractClass says: I am doing the bulk of the work\n"; } voidBaseOperation2(){ std::cout << "AbstractClass says: But I let subclasses override some operations\n"; } voidBaseOperation3(){ std::cout << "AbstractClass says: But I am doing the bulk of the work anyway\n"; } // 将需要由具体类实现的步骤声明为虚函数 // 变化部分 virtualvoidRequiredOperations1()= 0; virtualvoidRequiredOperation2()= 0; // 这些方法不是强制的要求具体类实现,因为他们已经被定义了(虽然并不做任何动作) // 它们可以为算法模板提供一些可供具体类修改的扩展点 virtualvoidHook1(){} virtualvoidHook2(){} };
intmain(){ std::cout << "Same client code can work with different subclasses:\n"; ConcreteClass1 *concreteClass1 = new ConcreteClass1; ClientCode(concreteClass1); std::cout << "\n"; std::cout << "Same client code can work with different subclasses:\n"; ConcreteClass2 *concreteClass2 = new ConcreteClass2; ClientCode(concreteClass2);
Execution result: Same client code can work with different subclasses: AbstractClass says: I am doing the bulk of the work ConcreteClass1 says: Implemented Operation1 AbstractClass says: But I let subclasses override some operations ConcreteClass1 says: Implemented Operation2 AbstractClass says: But I am doing the bulk of the work anyway
Same client code can work with different subclasses: AbstractClass says: I am doing the bulk of the work ConcreteClass2 says: Implemented Operation1 AbstractClass says: But I let subclasses override some operations ConcreteClass2 says: Overridden Hook1 ConcreteClass2 says: Implemented Operation2 AbstractClass says: But I am doing the bulk of the work anyway