Java Design Pattern cainiao series (10) template method pattern modeling and implementation
Template Method: defines the skeleton of an algorithm in a Method, and delays some steps to the subclass. The template method allows the subclass to redefine some steps in the algorithm without changing the algorithm structure. In short, the template method defines an algorithm step and allows sub-classes to provide implementation for one or more steps.
I. uml modeling:
Ii. Code implementation:
/*** Example: the template method defines the steps of an algorithm and allows subclasses to be implemented by one or more steps. ** Taking eating as an example: Most people like to eat with chopsticks, but some still eat with a spoon */abstract class AbstractTemplate {public void into hands () {System. out. println (wash your hands before meals ...);} /*** extract the method of eating --> Template Method */public abstract void eatWay (); public void rest () {System. out. println (rest after meals ...);}} class EatByChopsticks extends AbstractTemplate {@ Overridepublic void eatWay () {System. out. println (most people prefer to eat with chopsticks ...);}} class EatBySpoon extends acttemplate {@ Overridepublic void eatWay () {System. out. println (some eat with a spoon ...);}} /*** client Test class ** @ author Leo */public class Test {public static void main (String [] args) {AbstractTemplate at1 = new EatByChopsticks (); at1.eatWay (); abstractTemplate at2 = new EatBySpoon (); at2.eatWay ();}}
Iii. Summary
Template Method mode: in an abstract class, there is a main method, and then defines 1... n methods can be abstracted and not abstract. Define sub-classes to inherit the abstract class, override the abstract method, and call the abstract class to call the sub-class.