Template method pattern: Define the skeleton of an algorithm in an operation, while deferring some steps to subclasses. Template methods allow subclasses to redefine specific steps of an algorithm without changing the structure of the algorithm.
A suitable time: When we want to complete a process or a series of steps that are consistent at a certain level of detail, but the implementation of individual steps at a more detailed level may be different, we usually consider using templates Method pattern to handle.
Two roles of the template method:
Abstract Class (AbstractClass): Gives the framework of top-level logic
Concrete Product Class (ConcreteClass): When implementing the definition of the parent class One or more abstract methods. An AbstractClass can have multiple ConcreteClass.
Structure diagram:
[code]int main(){ AbstractClass *pAbstractA = new ConcreteClassA; pAbstractA->TemplateMethod(); //Output: ConcreteA Operation1 ConcreteA Operation2 AbstractClass *pAbstractB = new ConcreteClassB; pAbstractB->TemplateMethod(); //Output: ConcreteB Operation1 ConcreteB Operation2 if(pAbstractA) delete pAbstractA; if(pAbstractB) delete pAbstractB; return 0; }
[code]class AbstractClass{ public: void TemplateMethod(){ //统一的对外一个接口 PrimitiveOperation1(); PrimitiveOperation2(); } protected: virtual void PrimitiveOperation1(){ //原始操作1 std::cout << "Default Operation1\n"; } virtual void PrimitiveOperation2(){ //原始操作2 std::cout << "Default Operation2\n"; } }; class ConcreteClassA: public AbstractClass{ protected: //重载方法1和2 virtual void PrimitiveOperation1(){ std::cout << "ConcreteA Operation1\n"; } virtual void PrimitiveOperation2(){ std::cout << "ConcreteA Operation2\n"; } }; class ConcreteClassB: public AbstractClass{ protected: virtual void PrimitiveOperation1(){ std::cout << "ConcreteB Operation1\n"; } virtual void PrimitiveOperation2(){ std::cout << "ConcreteB Operation2\n"; } };
The template method pattern reflects its advantages by moving unchanged behavior to the parent class and removing duplicate code in the subclass.
The template method pattern provides a good code reuse platform.