Template Method Pattern (Templatemethod), which 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.
Structure diagram:
Code:
Algorithm skeleton:
1 Package Cn.happy.design_pattern._07templatemethod;2 3 Public Abstract classAbstractClass {4 5 Public Abstract voidPrimitiveOperation1 ();6 Public Abstract voidPrimitiveOperation2 ();7 Public voidTemplatemethod () {8 PrimitiveOperation1 ();9 PrimitiveOperation2 ();Ten } One}
Some of the steps of overriding an algorithm skeleton:
1 Package Cn.happy.design_pattern._07templatemethod;2 3 Public classConcreteclassa extends AbstractClass {4 5 @Override6 Public voidPrimitiveOperation1 () {7System. out. println ("Concrete Class A Method 1 implementation");8 9 }Ten One @Override A Public voidPrimitiveOperation2 () { -System. out. println ("Concrete Class A Method 2 implementation"); - the } - - } - Public classConcreteclassb extends AbstractClass { + - @Override + Public voidPrimitiveOperation1 () { ASystem. out. println ("Concrete Class B Method 1 Implementation"); at - } - - @Override - Public voidPrimitiveOperation2 () { -System. out. println ("Concrete Class B Method 2 implementation"); in - } to +}
Test class:
1 Package Cn.happy.design_pattern._07templatemethod;2 3 Public classMmain {4 5 Public Static voidMain (string[] args) {6AbstractClass C =NewConcreteclassa ();7 C.templatemethod ();8c =NewCONCRETECLASSB ();9 C.templatemethod ();Ten One } A -}
Java Learning notes-design pattern Vii. Template Method pattern