23 design modes (6): Template Method Mode

Source: Internet
Author: User

Definition:Defines the framework of an algorithm in an operation, and delays some steps to the subclass so that the subclass can redefine some specific steps of the Algorithm without changing the structure of the algorithm.

Type:Behavior mode

Class diagram:

In fact, the template method is a commonly used mode in programming. Let's look at an example. programmer A obtains a task one day: given an integer array, sorts the number in the array from small to large, and then prints the sorted result. After analysis, this task can be divided into two parts: sorting and printing. The printing function is good, and sorting is a little troublesome. However, there is a way to complete the printing function first, and the sorting function is done by someone else.

Abstract class sort actsort {/*** sorts the array from small to large * @ Param array */protected abstract void sort (INT [] array ); public void showsortresult (INT [] array) {This. sort (array); system. out. print ("sorting result:"); For (INT I = 0; I <array. length; I ++) {system. out. printf ("% 3 s", array [I]) ;}}

After writing this article, a found his new employee B and said, "I have already completed the main logic of a task. Please implement the remaining logic. Therefore, the abstractsort class is assigned to B and B is written for implementation. B. The Code is as follows:

Class concretesort extends actsort {@ overrideprotected 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 variable int indexmin = 0; // min index variable int temp; // temporary variable for (INT I = index; I <array. length; I ++) {If (array [I] <minvalue) {// find the minimum value minvalue = array [I]; // store the minimum value indexmin = I ;}} temp = array [Index]; // exchange two values: array [Index] = array [indexmin]; array [indexmin] = temp ;}}

After writing it, give it to a and 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 ();}}

Running result:

Sorting result: 0 1 3 4 5 7 9 10 12 32

Running properly. The task is completed. That's right. This is the template method mode. Most of the new graduates should have experience similar to B. A complicated task is written by the cool people in the company to write the main logic, and then abstract the seemingly simple methods and hand them over to other colleagues for development. This division of labor is often used in companies with obvious levels of programmers. For example, if a project team has architects, senior engineers, and Junior engineers, architects generally use a large number of interfaces and abstract classes to concatenate the entire system logic, the implementation code is assigned to senior engineers and junior engineers Based on the difficulty. How is the template method used?

 

Structure of the template method mode

The template method mode consists of an abstract class and an (or a group) Implementation class that uses the inheritance structure. There are three methods in the abstract class:

  • Abstract method:The parent class only declares but does not implement it. Instead, it defines the specification and implements it by its subclass.
  • Template Method:It is declared and implemented by the abstract class. Generally, the template method calls abstract methods to complete the main logical functions. In addition, most template methods are defined as final types, indicating that the main logical functions cannot be overwritten in the subclass.
  • Hook method:It is declared and implemented by the abstract class. However, subclass can be expanded, and subclass 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, which is usually written by experienced personnel. The quality of the abstract class directly determines whether the program is stable.

Implementation class is used to implement details. The template method in the abstract class completes the business logic by implementing class extension. As long as the extension method in the implementation class passes the unit test, the overall function will not produce major errors 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 change, while the abstract method is easy to reverse change. Therefore, by adding implementation classes, it is generally easy to implement function expansion, in line with the principle of open and closed.

Easy to maintain. For the template method mode, the template method is used because their main logic is the same. If the template method is not used, the same code is distributed across different classes, it is very inconvenient to maintain.

Flexible. Because of the hook method, the implementation of sub-classes can also affect the operation of the main logic in the parent class. However, while being flexible, child classes affect the parent class and violate the Lee's replacement principle, which also brings risks to the program. This has higher requirements on the design of abstract classes.

When multiple subclasses have the same method, and these methods have the same logic, you can consider using the template method mode. This mode is also suitable for applications with the same main framework and different details.

From: http://blog.csdn.net/zhengzhb/article/details/7405608

 

Definition:Defines the framework of an algorithm in an operation, and delays some steps to the subclass so that the subclass can redefine some specific steps of the Algorithm without changing the structure of the algorithm.

Type:Behavior mode

Class diagram:

In fact, the template method is a commonly used mode in programming. Let's look at an example. programmer A obtains a task one day: given an integer array, sorts the number in the array from small to large, and then prints the sorted result. After analysis, this task can be divided into two parts: sorting and printing. The printing function is good, and sorting is a little troublesome. However, there is a way to complete the printing function first, and the sorting function is done by someone else.

Abstract class sort actsort {/*** sorts the array from small to large * @ Param array */protected abstract void sort (INT [] array ); public void showsortresult (INT [] array) {This. sort (array); system. out. print ("sorting result:"); For (INT I = 0; I <array. length; I ++) {system. out. printf ("% 3 s", array [I]) ;}}

After writing this article, a found his new employee B and said, "I have already completed the main logic of a task. Please implement the remaining logic. Therefore, the abstractsort class is assigned to B and B is written for implementation. B. The Code is as follows:

Class concretesort extends actsort {@ overrideprotected 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 variable int indexmin = 0; // min index variable int temp; // temporary variable for (INT I = index; I <array. length; I ++) {If (array [I] <minvalue) {// find the minimum value minvalue = array [I]; // store the minimum value indexmin = I ;}} temp = array [Index]; // exchange two values: array [Index] = array [indexmin]; array [indexmin] = temp ;}}

After writing it, give it to a and 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 ();}}

Running result:

Sorting result: 0 1 3 4 5 7 9 10 12 32

Running properly. The task is completed. That's right. This is the template method mode. Most of the new graduates should have experience similar to B. A complicated task is written by the cool people in the company to write the main logic, and then abstract the seemingly simple methods and hand them over to other colleagues for development. This division of labor is often used in companies with obvious levels of programmers. For example, if a project team has architects, senior engineers, and Junior engineers, architects generally use a large number of interfaces and abstract classes to concatenate the entire system logic, the implementation code is assigned to senior engineers and junior engineers Based on the difficulty. How is the template method used?

 

Structure of the template method mode

The template method mode consists of an abstract class and an (or a group) Implementation class that uses the inheritance structure. There are three methods in the abstract class:

  • Abstract method:The parent class only declares but does not implement it. Instead, it defines the specification and implements it by its subclass.
  • Template Method:It is declared and implemented by the abstract class. Generally, the template method calls abstract methods to complete the main logical functions. In addition, most template methods are defined as final types, indicating that the main logical functions cannot be overwritten in the subclass.
  • Hook method:It is declared and implemented by the abstract class. However, subclass can be expanded, and subclass 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, which is usually written by experienced personnel. The quality of the abstract class directly determines whether the program is stable.

Implementation class is used to implement details. The template method in the abstract class completes the business logic by implementing class extension. As long as the extension method in the implementation class passes the unit test, the overall function will not produce major errors 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 change, while the abstract method is easy to reverse change. Therefore, by adding implementation classes, it is generally easy to implement function expansion, in line with the principle of open and closed.

Easy to maintain. For the template method mode, the template method is used because their main logic is the same. If the template method is not used, the same code is distributed across different classes, it is very inconvenient to maintain.

Flexible. Because of the hook method, the implementation of sub-classes can also affect the operation of the main logic in the parent class. However, while being flexible, child classes affect the parent class and violate the Lee's replacement principle, which also brings risks to the program. This has higher requirements on the design of abstract classes.

When multiple subclasses have the same method, and these methods have the same logic, you can consider using the template method mode. This mode is also suitable for applications with the same main framework and different details.

From: http://blog.csdn.net/zhengzhb/article/details/7405608

 

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.