Template method mode for the Java design pattern

Source: Internet
Author: User

1. An example of a template method

This section focuses on the template method pattern in design mode. Let's take a look at an example: what would you do if the boss asked you to make a model of a car and ask for the basic functionality to be done, regardless of extensibility? We will first design a class diagram based on experience:

From this class diagram, it is very simple to implement the Hummer, the car has two models of H1 and H2. Now that we are starting to implement these two models of Hummer, first we have to write the abstract class, and then two different model implementation classes through simple inheritance can achieve the requirements. First look at the code for the abstract class:

Public abstract class Hummermodel {public abstract void start ();//Launch public abstract void Stop ();  Stop public abstract void alarm (); Whistle public abstract void engineboom (); Roar public abstract void run (); The car's going to run.
Simple enough, let's implement the two Hummer models:

Hummer H1public class HummerH1 implements Hummermodel {@Overridepublic void start () {System.out.println ("H1 launch ..."); @Overridepublic void Stop () {System.out.println ("H1 stop ..."); @Overridepublic void Alarm () {System.out.println ("H1 whistle ..."); @Overridepublic void Engineboom () {System.out.println ("H1 roar ..."); @Overridepublic void Run () {This.start (); This.engineboom (); This.alarm (); This.stop ();}} Hummer H2public class HummerH2 implements Hummermodel {     @Override     public void Start () {         system.out.println ("H2 launch ...");    }    @ override    public void Stop () {        system.out.println ("H2 stop ...");     }     @Override     public void alarm () {         SYSTEM.OUT.PRINTLN ("H2 whistle ...");    }     @Override      public void Engineboom () {     &nbsP  system.out.println ("H2 roar ...");    }     @Override     public void Run () {        this.start ();        this.engineboom ();         this.alarm ();        this.stop ();    }}
Obviously, the code has been found to be a bit problematic, and the two Hummer's Run method is exactly the same. So this run method should appear in the abstract class, not in the implementation class, abstraction is the generic encapsulation of all subclasses. So let's modify the abstract class:

Public abstract class Hummermodel {public abstract void start ();//Launch public abstract void Stop ();  Stop public abstract void alarm (); Whistle public abstract void engineboom (); Roar public void Run () {//car will always run This.start (); This.engineboom (); This.alarm (); This.stop ();}
So two implementation classes do not have to implement the Run method, can be directly used. In fact, this is the template method pattern.

2. Definition of template method pattern

The template method pattern is simple, and it is defined as: Define The skeleton of an algorithm in a operation, deferring some steps to subclasses. Template Method lets subclasses define certain steps of an algorithm without changing the algorithm ' s structure. That is, defining an algorithmic framework in an operation, and delaying some steps into subclasses so that subclasses can define some specific steps of the algorithm without altering the structure of an algorithm. The general class diagram for the template method pattern is as follows:

The template method pattern is really simple, just using the Java inheritance mechanism, but it is a very widely used pattern, where abstractclass is called abstract template, its methods are divided into two categories: the Basic method (subclass to implement) and the template method (can have one or more, that is, a framework, Implement the basic method of scheduling, complete the fixed logic). To prevent malicious operations, the general template method adds the final keyword, which is not allowed to overwrite. Let's take a look at the AbstractClass template:

Public abstract class AbstractClass {//basic method protected abstract void DoSomething ();p rotected abstract void doanything ();// Template method public void Templatemethod () {//Call basic method, complete related logic this.doanything (); this.dosomething ();}}
The concrete implementation class will not write ...

3. Advantages and disadvantages of template method mode

Advantages:

1) package The invariant part, extend the variable part: the algorithm that considers the invariant part is encapsulated in the parent class implementation, the variable part can be implemented by inheritance, it is easy to extend.

2) Extract the public part code for ease of maintenance: The Hummer example above is a good explanation.

3) behavior is controlled by the parent class and implemented by subclasses.

Disadvantages:

The template method pattern reverses our usual design habits: abstract classes are responsible for declaring the most abstract, most general attributes and methods of things, implementing classes to implement specific properties and methods of things. It can be difficult to read code in complex projects.

4. Extension of template Method mode

Or the above Hummer example, now the boss said this car why run up to whistle, too noisy, should not let the user decide whether it should whistle it? It seems to be true ... Well, we can modify the methods in the abstract template class:

Public abstract class Hummermodel {protected abstract void start ();//launch protected abstract void Stop ();  Stop protected abstract void alarm (); Whistle protected abstract void engineboom (); Roar final public void run () {//The car will always run This.start (); This.engineboom (); if (This.isalarm ()) {//Want it to be called, not to call This.alarm ();} This.stop ();} Protected Boolean isalarm () {//We have added a method of judgment, which returns Truereturn true by default;}}
We have added a method in the template class to determine whether to whistle, and now it is good to do, the concrete implementation of the class as long as the override of this method can be used to control whether or not to whistle, let's look at the implementation of the class:

public class HummerH1 extends Hummermodel {private Boolean alarmflag = true;//judgment tag @overridepublic void start () {System.ou T.println ("H1 launch ..."); @Overridepublic void Stop () {System.out.println ("H1 stop ..."); @Overridepublic void Alarm () {System.out.println ("H1 whistle ..."); @Overridepublic void Engineboom () {System.out.println ("H1 roar ..."); @Overrideprotected Boolean isalarm () {//Overwrite Isalarm method, return judgment token return this.alarmflag;} public void Setalarm (Boolean isalarm) {//set judgment token This.alarmflag = Isalarm;}}
This implementation is very good, we define a judgment tag in the implementation class, and then provide a public interface setalarm to let the outside world set this judgment tag, it is like a switch, want to let it ture and false is OK. This isalarm method is commonly known asHook Method。 The template method with the hook method is perfect, and you can imagine that a method return value of a subclass determines the execution result of the public part, which is attractive. Let's test it out:

public class Test {public static void main (string[] args) throws IOException {System.out.println ("----H1 type Hummer----"); System.out.println ("Do you need a horn sound?") 0-does not require  1-need "); String type = new BufferedReader (new InputStreamReader (system.in)). ReadLine (); HummerH1 H1 = new HummerH1 (), if (Type.equals ("0")) {H1.setalarm (false);} H1.run ();}}

When different instructions are entered, different actions are decided: that is, to avoid the whistle, so far, this template method mode is finished.

Related reading: http://blog.csdn.net/column/details/des-pattern.html

___________________________________________________________________________________________________________ __________________________________________

-----willing to share and progress together!

-----More articles please see: http://blog.csdn.net/eson_15

Template method mode for the Java design pattern

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.