Template method Mode
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. Popular is that there are a lot of the same steps, in some places there may be some differences suitable for this mode, such as the big talk design mode in the test scenario, everyone's paper is the same, only the answer is not the same. This scenario is appropriate for the template method pattern. I wrote this time is a car start-up process, each kind of car start process is basically the same process, but there are some small differences in the process.
Template method Mode UML diagram
Template Method Pattern Code
Packagecom.roc.template;/*** Car Model * Model mode *@authorLIAOWP **/ Public Abstract classCarmodel {/*** Car Start-up*/ protected Abstract voidstart (); /*** Parking*/ protected Abstract voidStop (); /*** Users do not need to pay attention to how your car starts or stops, can be opened can be stopped on it*/ Final Public voidExcet () { This. Start (); This. Stop (); }}
package com.roc.template; /** Volkswagen * @author LIAOWP * */ public class Wcar extends carmodel{@Override protected void start () {System.out.pri NTLN ( Volkswagen car start ....) Sudden Dodo "); } @Override protected void Stop () {System.out.println ( "Volkswagen car parking ... "); }}
Package com.roc.template; Public class extends carmodel{ @Override protectedvoid start () { System.out.println ( "Audi keyless start burst"); } @Override protectedvoid Stop () { System.out.println ("Audi Parking "); }}
Packagecom.roc.template;/*** Client *@authorLIAOWP **/ Public classClient { Public Static voidMain (string[] args) {Carmodel wcar=NewWcar ();//The first car in the family, as a user we do not need to focus on how the car started. The subclass variable becomes the parent class. polymorphicWcar.excet (); //Suddenly, the family needs a second car. Audi, we don't have to pay attention to how he started the production.Carmodel ocar=NewOcar (); Ocar.excet (); }}
Template method Pattern Applicable scenario
- One-time implementation of an invariant part of the algorithm, and the variable behavior is left to subclass to achieve.
- The public behavior in each subclass should be extracted and centralized into a common parent class to avoid code duplication. This is a good example of what Opdyke and Johnson described as "re-factoring to generalize." First identify the differences in the existing code and separate the differences into new operations. Finally, replace these different code with a template method that invokes these new operations.
- Controls the subclass extension. The template method invokes the "hook" operation only at a specific point, so that only those points are allowed to be extended.
Patterns of template methods for Java design patterns