Reprint Please specify source: http://blog.csdn.net/lhy_ycu/article/details/39806973
Template method Mode: A skeleton of an algorithm is defined in a method, and some steps are deferred to subclasses. The template method allows subclasses to redefine some of the steps in the algorithm without changing the structure of the algorithm. In short: The template method defines the steps of an algorithm and allows subclasses to provide implementations for one or more steps.
First, UML modeling:
Second, the code implementation:
/** * Example: A template method defines the steps of an algorithm and allows subclasses to provide implementations for one or more steps. * take a meal as an example: most people like to eat with chopsticks, but some eat with a spoon */abstract class Abstracttemplate {public void Washhands () {System.out.println (" Wash your hands before meals ... "); /** * Extract the way you eat--template method */public abstract void Eatway ();p ublic Void Rest () {System.out.println ("Rest after dinner ...");} Class Eatbychopsticks extends Abstracttemplate {@Overridepublic void Eatway () {System.out.println ("Most people like to eat with chopsticks ...");}} Class Eatbyspoon extends Abstracttemplate {@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 E Atbychopsticks (); At1.eatway (); Abstracttemplate AT2 = new Eatbyspoon (); At2.eatway ();}}
Iii. Summary
Template method Pattern: In an abstract class, there is a main method, and then define 1...N methods, can be abstract, can not be abstract, define subclasses inherit the abstract class, override abstract methods, by invoking the abstract class, implement the call of the subclass.
Java Design Patterns Rookie series (10) Modeling and implementation of template method pattern