Template mode defines a template for a method in the parent class, and the subclass can dynamically implement the template composition method, but the order of the methods in the template cannot be changed.
The template method in the parent class is often declared final, to ensure that the method is not covered by the quilt, because as a template, it can not be changed, but a series of methods within the template method can be statically implemented by subclasses, and in the parent class template method, you can define the hook (hook) method. Facilitates the optimization of the subclass for the template method. The following two examples illustrate.
/*no hook template method, the template method cannot be modified at this time*/ Public Abstract classModel { Public Final voidEat ()/*Template Method*/{Preparefood (); Cookfood (); Eatfood (); } Public Abstract voidPreparefood ();//the method of giving to subclasses to implement Public Abstract voidCookfood ();//the method of giving to subclasses to implement Public Abstract voidEatfood ();//the method of giving to subclasses to implement}classGirlextendsModel {/*after the subclass implements the method to be implemented, the template method can be called to complete the operation*/@Override Public voidPreparefood () {System.out.println ("The girls are preparing their meals!"); } @Override Public voidCookfood () {System.out.println ("The girls are cooking!"); } @Override Public voidEatfood () {System.out.println ("The girls are eating!"); } }
/*a template method with hooks, at which time the template can be freely modified by subclasses*/ Public Abstract classModel { Public Final voidEat ()/*Template Method*/{Preparefood (); if( Hook ())) Cookfood (); Eatfood (); } Public BooleanHook () {return true; } Public Abstract voidPreparefood ();//the method of giving to subclasses to implement Public Abstract voidCookfood ();//the method of giving to subclasses to implement Public Abstract voidEatfood ();//the method of giving to subclasses to implement}classGirlextendsModel {/*after the subclass implements the method to be implemented, the template method can be called to complete the operation*/@Override Public voidPreparefood () {System.out.println ("The girls are preparing instant noodles!"); } @Override Public voidCookfood () {System.out.println (""); } @Override Public voidEatfood () {System.out.println ("The girls are eating instant noodles!"); } Public BooleanHook ()/*after this method returns to false in the subclass, the Cook method cannot be called, so the template method is changed, which is called the "hook", which can change the template method.*/ { return false; }}
Design Pattern Collation _ template mode