Template method Pattern of Java pattern Design in layman's way

Source: Internet
Author: User

First, the Primer

This is a very simple pattern, but it is very widely used. The simple reason is that only the inheritance relationship is used in this pattern.

Due to their own shortcomings, the inheritance relationship was deducted by experts as "evil" hats. "Use delegated relationships instead of inheritance", "Try to use interface implementations instead of abstract class inheritance" and so on expert warnings, let us these rookie to inherit "the".

In fact, there are many advantages of inheritance. It seems that the disadvantage of being abused by everyone is more obvious. The rational use of inheritance relationship, or can be a good role in the design of your system. and the template method pattern is one of the use examples.

  II. Definition and structure

GOF defines the skeleton of an algorithm in an operation to the template method pattern, and delays some steps into subclasses. Enables subclasses to redefine some specific steps of the algorithm without altering the structure of an algorithm. The structure of the algorithm here can be understood as a business process that you design based on your needs. Specific steps are those that may have variables in the content.

As you can see, the template method pattern is also designed to subtly address the impact of changes on the system. The use of template methods to enhance system extensibility, minimizing the impact of changes on the system. This, in the following example can be clearly seen.

Let's look at the structure of this simple pattern:

1) AbstractClass (abstract Class): One or more abstract methods are defined for specific subclasses to implement them, and a template method is implemented to define the skeleton of an algorithm. The template method not only invokes the previous abstract method, but also invokes other operations, as long as it can accomplish its own mission.

2) Concreteclass (concrete Class): Implements the abstract method in the parent class to complete the steps associated with a particular subclass in the algorithm.

The following is a schematic diagram of the template method pattern. Just take the diagram from the design pattern and use it:


  Iii. examples

Or just find an example of JUnit in the source code of my analysis. The testcase in JUnit and its subclasses are examples of a template method pattern. In TestCase this abstract class, the entire test process is set up, such as first executing the Setup method to initialize the test premise, running the test method, and then teardown to cancel the test settings. But what are you going to do in Setup and teardown? Who knows!! Therefore, the implementation of these steps is deferred to the subclass, which is the test class that you implement.

Take a look at the relevant source code.

This is the template method for executing the test in testcase. As you can see, it has developed the framework of the "algorithm", as stated in the previous definition, by first executing the Setup method to initialize it, then executing the test method, and finally executing the teardown releasing the resources you have received.

public void Runbare () throws Throwable {
SetUp ();

try {
Runtest ();
}

finally {
TearDown ();
}
}


This is the two methods used above. Unlike the definition, these two methods are not implemented as abstract methods, but are two empty inaction methods (called hook methods). This is because in testing, we do not have to let the test program use both methods to initialize and release resources. In the case of abstract methods, subclasses must give it an implementation, regardless of the use. This is obviously unreasonable. With the hook method, you can override these methods in subclasses when you need them.

protected void SetUp () throws Exception {}
protected void TearDown () throws Exception {}


Iv. Applicable situation

Based on the analysis of the above definition and the description of the example, you can see that the template method is suitable for the following situations:

1) One-time implementation of an invariant part of the algorithm, and the variable behavior is left to subclass to achieve.

2) The public behavior of each subclass should be extracted and centralized into a common parent class to avoid code duplication. In fact, this can be said to be a good coding habit.

3) Control sub-class extension. The template method invokes the operation only at a specific point, so that only those points are allowed to be extended. For example, the Runbare () method above applies the Setup method only in front of Runtest. If you do not want the subclass to modify the framework of your template method definition, you can do it in two ways: one is not to show your template method in the API, and the other is to set your template method to final.

It can be seen that using the template method pattern can extract the common behavior of code and achieve the purpose of reuse. Also, in the template method pattern, the template method of the parent class is used to control the specific implementation in the subclass. This way you do not need to have much knowledge of the business process when implementing subclasses.

(Ai92 Editor: Ark)

Template method Pattern of Java pattern Design in layman's way

Related Article

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.