Structure diagram:
Realize:
1 Abstract classAbstractClass2 {3 Abstract voidPrimitiveOperation1 ();//deferred to subclass implementation4 Abstract voidPrimitiveOperation2 ();//deferred to subclass implementation5 6 Public voidTemplatemethod ()7 {8 PrimitiveOperation1 ();9 PrimitiveOperation2 ();Ten One } A - } - the classConcreteclassaextendsabstractclass{ - - voidPrimitiveOperation1 () - { +System.out.println ("Concrete Class A method one implementation"); - } + A voidPrimitiveOperation2 () at { -System.out.println ("Concrete Class A method two implementations"); - } - } - - classConcreteclassbextendsabstractclass{ in voidPrimitiveOperation1 () - { toSystem.out.println ("Concrete class B method one implementation"); + } - the voidPrimitiveOperation2 () * { $System.out.println ("Concrete class B Method II Implementation");Panax Notoginseng } - } the + Public classTemplatemethod { A Public Static voidMain (string[] args) the { + AbstractClass C; - $c =NewConcreteclassa (); $ C.templatemethod (); - -c =NewCONCRETECLASSB (); the C.templatemethod (); - }Wuyi the -}
Application:
The template method abstracts the repeated behavior into the parent class, and some specific implementations of the algorithm framework are defined by subclasses, increasing the code reuse rate.
Design Patterns-Template methods