Template method Pattern: Defines the skeleton of an algorithm in an operation, and delays some steps into subclasses. The template method allows subclasses to redefine some specific steps of the algorithm without altering the structure of an algorithm.
A time to apply: 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 not be the same, we usually consider using a template method pattern to handle it.
Two roles for a template method:
Abstract class (AbstractClass): A framework for top-level logic
Specific product class (Concreteclass): Implements one or more abstract methods when the parent class is defined. A abstractclass can have multiple concreteclass.
Structure diagram:
Test Case:
[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;}
Template Method Implementation:
[code]class abstractclass{public:void Templatemethod () {//Unified external interface Primi TiveOperation1 (); PrimitiveOperation2 (); }protected:virtual void PrimitiveOperation1 () {//original operation 1 std::cout << "Default operation1\n"; } virtual void PrimitiveOperation2 () {//original operation 2 std::cout << "Default operation2\n"; }};class concreteclassa:public abstractclass{protected://Overloaded methods 1 and 2 virtual void PrimitiveOperation1 () {STD::C Out << "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"; }};
Template Method Features:
The template method pattern shows its advantages by moving the invariant behavior to the parent class and removing the duplicated code in the subclass.
The template method pattern is a great way to provide a good code reuse platform.
The above is the C + + design mode of the template approach to the content of the model, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!