Introduction to the template method model of Java design pattern _java

Source: Internet
Author: User

The template method pattern of the Java design Pattern defines the framework of an operation's algorithm, and delays some steps into subclasses so that subclasses can redefine certain steps in the algorithm without altering the structure of the algorithm . belong to behavior class pattern

As shown in the following illustration:

In fact, the template approach is a pattern that is often used in programming. For example, one day, programmer a gets a task: Given an array of integers, sort the numbers in the array from small to large, and then print out the results after the order. After analysis, this task can be divided into two parts, sorting and printing, printing function is good to achieve, sort of a bit troublesome. But a has the method, first completes the printing function, the sorting function other person does.

Abstract class Abstractsort {
 /**
 * Sorts array arrays from small to large
 * @param array
 /protected abstract void sort ( Int[] array);
 public void Showsortresult (int[] array) {
 this.sort (array);
 System.out.print ("Sort result:");
 for (int i = 0; i < Array.Length i++) {
  System.out.printf ("%3s", Array[i]);}
 }


After writing, a found a newly graduated colleague B said: "There is a task, the main logic I have written, you put the rest of the logic to achieve it." So the Abstractsort class to B, let B write implementation. b Take a look, too easy, 10 minutes, the code is as follows:

Class Concretesort extends Abstractsort {

 @Override
 protected void sort (int[) array) {for
 (int i=0; i< Array.length-1; i++) {
  selectsort (array, i);
 }
 }
 
 private void Selectsort (int[] array, int index) {
 int minvalue = 32767;//min value variable
 int indexmin = 0;//min index variable 
   
    int Temp; Staging variable for
 (int i = index; i < Array.Length i++) {
  if (Array[i] < MinValue) {//find minimum
  minvalue = AR Ray[i]; Store minimum value
  indexmin = i 
  }
 }
 Temp = Array[index]; Exchange of two numerical
 array[index] = array[indexmin];
 Array[indexmin] = Temp;
 }
}


   

Write it and give it to A,a for a run:

public class Client {public
 static int[] A = {10, 32, 1, 9, 5, 7, 12, 0, 4, 3};//Preset data array public
 static void Main (string[] args) {
 abstractsort s = new Concretesort ();
 S.showsortresult (a);
 }


Run Result:
Sort results: 0 1 3 4 5 7 9 10 12 32

Run normally. OK, the task is complete. Yes, this is the template method mode. Most graduates who have just entered the workforce should have experience like B. A complex task, in which the bull in the company writes the main logic, and then abstracts the seemingly simpler methods into the hands of other colleagues to develop them. This kind of division of labor in the level of programming staff is more obvious in the company often used. For example, a project team, there are architects, senior engineer, Junior engineers, then generally by the architect using a large number of interfaces, abstract classes to the entire system of logic, the implementation of the coding according to the different difficulty of the senior engineer and junior engineers to complete. How do you use the template method mode?

the structure of the template method pattern:

The template method pattern consists of an abstract class and a (or a group of) implementation classes that consist of an inheritance structure, and the methods in the abstract class are divided into three types:

1. Abstract method : The parent class declares but does not implement, but defines the specification and then implements it by its subclasses.

2. Template Method : By the abstract class declaration and implementation. In general, the template method invokes an abstract method to accomplish the primary logical function, and most of the template methods are defined as final types, indicating that the primary logical functionality cannot be overridden in subclasses.

3. Hook method : declared by an abstract class and implemented. But subclasses can be extended, and subclasses can influence the logic of the template method by extending the hook method.

The task of an abstract class is to build a logical framework, usually written by an experienced person, because the quality of an abstract class directly determines the stability of the program.

Implementation classes are used to implement the details. The template method in an abstract class is precisely the way to complete the business logic by implementing class extensions. As long as the extension method in the implementation class has passed the unit test, the overall function will not appear big error under the premise of correct template method.

The advantages of template method and the applicable scene:

Easy to expand. In general, the template method in the abstract class is not easy to reverse the change of the part, and the abstract method is easy to reverse the change of the part, so by adding the implementation class can easily achieve the extension of the function, in line with the opening and closing principle.

Easy to maintain. For template method mode, it is because their main logic is the same, only use the template method, if not using the template method, let these same code scattered in different classes, maintenance is very inconvenient.

More flexible. Because of the hook method, the implementation of the subclass can also affect the operation of the main logic in the parent class. However, at the same time, because the subclass affects the parent class, violating the principle of the Richter substitution, it also poses a risk to the program. This has a higher demand for the design of abstract classes.

You can consider using a template method pattern when multiple subclasses have the same method, and the methods are logically identical. It is also appropriate to use this pattern when the main frame of the program is the same and the details are different.

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.