design mode (Java)--task assignment in Template method mode

Source: Internet
Author: User

Turn from: http://blog.csdn.net/zhengzhb/article/details/7405608

definition: defines a framework for an algorithm in an operation, and delays some steps into subclasses so that subclasses can redefine some specific steps in the algorithm without altering the structure of the algorithm.

Type: behavior class mode

Class Diagram:

In fact, the template approach is a frequently used pattern in programming. Let's take a look at an example, a day when 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 sorted results. After analysis, this task can be broadly divided into two parts, sorting and printing, printing function is good to achieve, sorting is a bit troublesome. But a has the method, first the print function completes, the sorting function other people to do.

Abstract classAbstractsort {/*** Sort array from small to large *@paramArray*/    protected Abstract voidSortint[] array);  Public voidShowsortresult (int[] Array) {         This. Sort (array); System.out.print ("Sort Result:");  for(inti = 0; i < Array.Length; i++) {System.out.printf ("%3s", Array[i]); }    }}

After writing, a to find a colleague who just graduated from work, B said: There is a task, the main logic I have written, you put the rest of the logic to realize it. So the Abstractsort class to B, let B write implementation. b Take a look, it's too easy, 10 minutes to fix, the code is as follows:

classConcretesortextendsAbstractsort {@Overrideprotected voidSortint[] Array) {         for(inti=0; i<array.length-1; i++) {selectsort (array, i); }    }        Private voidSelectsort (int[] Array,intindex) {        intMinValue = 32767;//Minimum value variable        intindexmin = 0;//Minimum value index variable        intTemp;//Staging Variables         for(inti = index; i < Array.Length; i++) {            if(Array[i] < MinValue) {//Find minimum ValueMinValue = Array[i];//Store Minimum ValueIndexmin =i; }} Temp= Array[index];//Exchange two valuesArray[index] =Array[indexmin]; Array[indexmin]=Temp; }}
View Code

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

 Public class Client {    publicstaticint//  preset data array public      staticvoid  main (string[] args) {        new  concretesort ();        S.showsortresult (a);    }}
View Code

Operation Result:

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

is operating normally. All right, mission accomplished. Yes, this is the template method mode. Most graduates who have just entered the workplace should have experience similar to B. A complex task, by which the Bulls in the company write the main logic, and then put those seemingly simpler methods into abstractions and hand them over to other colleagues to develop. This method of division of labor is often used in companies where the level of programmer is more obvious. For example, a project team, an architect, senior engineer, junior engineer, generally by the architect use a large number of interfaces, abstract class will be the entire system of logic string up, the implementation of the code is based on the difficulty of the difference between the senior engineer and junior engineers to complete. How, is it used in the template method mode?

Structure of the template method pattern

The template method pattern consists of an abstract class and a (or a set of) implementation classes that are composed of inherited structures, and the methods in the abstract class are divided into three types:

    • Abstract Method: The parent class is declared but not implemented, but the specification is defined and then implemented by its subclasses.
    • Template method: declared by an abstract class and implemented. In general, the template method invokes an abstract method to complete the primary logical function, and most of the template methods are defined as final types, indicating that the primary logical function cannot be overridden in subclasses.
    • Hook method: declared and implemented by an abstract class. But subclasses can be extended, and subclasses can influence the logic of the template method by extending the hook method.
    • The task of abstract classes is to build a framework of logic, usually written by experienced personnel, because the quality of the abstract class directly determines the stability of the program.

Implementation classes are used to implement details. The template method in an abstract class accomplishes the business logic by implementing the method of class extension. As long as the extension method in the implementation class passes the unit test, the overall function is generally not big error if the template method is correct.

Advantages and application scenarios of the template method

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 increasing the implementation of the class can easily achieve the extension of the function, in line with the open and closed principle.

Easy to maintain. For the template method mode, it is because of their main logic is the same, the use of the template method, if you do not use the template method, let the 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 master logic in the parent class. However, at the same time, because the subclass affects the parent class, it violates the Richter scale substitution principle, and also poses a risk to the program. This has a higher demand for the design of abstract classes.

You can consider using the template method pattern when you have the same methods in multiple subclasses, and these methods are logically identical. This mode is also more suitable for applications where the main frame of the program is the same, with different details.

design mode (Java)--task assignment in Template method mode

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.