Template Method Mode: defines the skeleton of an algorithm in one method, and delays some steps into subclasses. The template method allows subclasses to redefine some of the steps in the algorithm without changing the structure of the algorithm.
This pattern is primarily used to create an algorithm template.
Hollywood principles: Don't Call (call) us, we'll call (call) you;
Application Case:
Array sorting algorithm void sort (object[] a), in which the argument object must implement the CompareTo (object o) method, that is, the import parameter object must implement the comparable interface.
Mode Demo Code:
#include <iostream>
/*caffeine: Caffeine, beverage: Beverages*/
classCaffeinebeverage
{
Public:
/*Algorithmic Templates*/
voidPreparerecipe ()
{
Boilwater ();//Boiling Water
Brew ();//Brewing
Pourincup ();//pour into cup
Addcondiments ();//Add Seasoning
}
voidBoilwater ()
{
std::cout<<"boiling water."<<std::endl;
}
voidPourincup ()
{
std::cout<<"pouring into Cup."<<std::endl;
}
VirtualvoidBrew () {};//virtual functions, subclasses must implement
VirtualvoidAddcondiments () {};
voidHook () {}//hook function, providing the default implementation, subclass selection implementation
};
/*Brew coffee based on the template method, only virtual functions are realized*/
classTea: PublicCaffeinebeverage
{
Public:
VirtualvoidBrew ()
{
std::cout<<"Dripping coffee through filter."<<std::endl;
}
VirtualvoidAddcondiments ()
{
std::cout<<"Adding Suger and milk."<<std::endl;
}
};
/*make tea based on template method, only realize virtual function*/
classCoffer: PublicCaffeinebeverage
{
Public:
VirtualvoidBrew ()
{
std::cout<<"steeping the tea."<<std::endl;
}
VirtualvoidAddcondiments ()
{
std::cout<<"Adding Lemon."<<std::endl;
}
};
intMain ()
{
std::cout<<"Template Method"<<std::endl;
Coffer coffer;
Coffer. Preparerecipe ();
Tea tea;
Tea. Preparerecipe ();
return0;
}
Template Method Mode template Mothod--learning headfirst design pattern record