Review design pattern (7)-template method pattern

Source: Internet
Author: User

1. Summary

In this article, we will give a comprehensive understanding of the template method mode.

2. Job Search Text message

Well, if you don't mind, I hope to make a job advertisement here.

Language direction: Java/C #/Vb. language familiarity is sorted in descending order.

Job orientation: development, testing, and other IT-related work.

Monthly salary: 1000 yuan or more

Work Location: Beijing

3. Open Doors

Template Method, defining an operationAlgorithmAnd some steps are delayed in the subclass.

Let's take a look at the template method: (from terrylee's. Net Design Mode-template method mode)

This mode is easy to understand and I will not draw it myself.

We can see that the key to this pattern is the templatemethod () method in the parent class, which provides the skeleton of our algorithm.

We have discussed design patterns with our friends. We agree that the template method is the most important design pattern in the gof23 design patterns, but we believe that this pattern, we do not need to regard him as a design pattern, or even a common inheritance rule.

4. Purpose of the template method

The purpose of the template method is as follows:

A. Reduce duplicatesCode.

B. Prevent call errors.

In this case, we will summarize the steps for using the template method:

A. Recognition

B. Separation

C. Implementation

That is to say, we should first find out from a series of algorithms where their common parts are called recognition. Then we extract different codes, which are called separation. Finally, we use inheritance to implement the extracted method in the subclass.

5. template method for Array Operations

In a complex algorithm, many nested algorithms are involved in an algorithm.

For example, we want to perform an operation on the nth object in an object ang array. In this way, we may need to divide the entire algorithm into three steps:

A. Sort the object arrays according to certain rules.

B. Find the nth largest number of object arrays. Maybe we don't know this n. Then this N may be read from the database, maybe from the file, or a random number.

C. perform an operation on this object, which may be deletion or modification to a property of this object.

So we need to write:

 Abstract class  Arrayoperate { Public void Templatemethod (){ List < People > Required learray = New  List < People > { New  People ( "111" , 1 ), New  People ( "222" , 2 ), New  People ( "333" , 3 ), New  People ( "444" , 4 ), New  People ( "555" , 5)}; sort ( Ref Peoplearray ); People P = findonepeople (optional learray); P = changesomeonename (p); display (p );} Public abstract void Sort ( Ref  List < People > Revoke learray ); Public Abstract  People Findonepeople ( List < People > Revoke learray ); Public Abstract  People Changesomeonename ( People P ); Public abstract void Display ( People P );}

 Class  Conoperate : Arrayoperate { Public override void Sort ( Ref List < People > Repeated learray) {repeated learray. Sort (sortpeople );} Public override  People Findonepeople ( List < People > Repeated learray ){ Random R = New  Random (); Int Randomint = R. Next (fig. Count ); Return Revoke learray [randomint];}Public override  People Changesomeonename ( People P) {P. Name = "123" ; Return P ;} Public override void Display ( People P ){ Console . Writeline ( "Name :" + P. Name + "\ N" + "Age :" + P. Age );} Private Static int Sortpeople (People P1, People P2 ){ Return  String . Compare (p1.name, p2.name );}}

ClassPeople{Private stringName;Private intAge;Public StringName {Get{ReturnName ;}Set{Name =Value;}}Public intAge {Get{ReturnAge ;}}PublicPeople (StringName,IntAge ){This. Name = Name;This. Age = age ;}}

ClassProgram{Static voidMain (String[] ARGs ){ArrayoperateAo =NewConoperate(); AO. templatemethod ();}}

Here, we can replace the method. We specify an execution process of the method in the parent class, and then require the subclass to implement the specific method.

6. In-depth study of the template method

Let's look at the returned results:

Template Method utility 1: saves subclass code.

In this way, if we abstract all the methods in the parent class, we will not reduce the subclass code.

Therefore, it is easy to write templates, but it is not so easy to write a good template method.

We need to achieve good extraction and put a fixed Implementation Method in the parent class method for implementation.

Template Method utility 2: prevents calling operations

In many books about the design pattern, the template method of the parent class is replaced by a simple method accumulation, such as display ** 1, display * 2, and so on. This creates an illusion for many readers that the template method is to call the following method, but it is not all about it.

7. Review the template-generic

I have always said that many implementations are provided in many advanced languages, such as C # and Java, which makes many models A concept rather than a necessary implementation.

In this section, we will discuss a thought variant of the template method-generic

In C #2.0, a very important feature-generic. We may see this in many reference books. The C # generic type is similar to the C ++ template.

In fact, the generic type of C # is also a thought variant of the template method. It provides the same template for different types.

8. Class explosion

Let's take a look at this situation. In the template method, if the same set of templates requires multiple extensions, do we have to write many inherited subclasses?

In this way, I need to mention a concept that I have mentioned countless times before: Explosion-this is a class explosion.

Suppose we want to perform one or more operations on an array. For example, we need to sort the array first and then how is it going.

For example, we may adopt different sorting methods based on different array structures. Some may use bubble, some use fast sorting, and some use merge. Then we have to write a corresponding subclass for each sort, which is troublesome.

What should I do? What should I do? What should I do?

9. Delegate event improvement Template Method

 Class  Program { Static void Main ( String [] ARGs ){Arrayoperate Ao = New  Conoperate (); AO. Sort + = New  Sortdelegate ( Delegate ( Ref  List < People > Peoplelist) {peoplelist. Sort (sortpeople) ;}); AO. templatemethod ();} Private Static int Sortpeople ( People P1, People P2 ){ Return  String . Compare (p1.name, p2.name );}} Public Delegate void  Sortdelegate ( Ref  List < People > List ); Abstract class  Arrayoperate { Public event  Sortdelegate Sort; Public void Templatemethod (){ List < People > Required learray = New  List < People > { New  People ( "111" , 1 ), New  People ( "222" , 2 ), New  People ( "333" , 3 ),New  People ( "444" , 4 ), New  People ( "555" , 5)}; sort ( Ref Peoplearray ); People P = findonepeople (optional learray); P = changesomeonename (p); display (p );} // Public abstract void sort (Ref List <people> revoke learray );  Public Abstract  People Findonepeople ( List < People > Revoke learray ); Public Abstract  People Changesomeonename ( People P ); Public abstract void Display ( People P );} Class  Conoperate : Arrayoperate { // Public override void sort (Ref List <people> specify learray) // {// specify learray. Sort (sortpeople );//}  Public override People Findonepeople ( List < People > Repeated learray ){ Random R = New  Random (); Int Randomint = R. Next (fig. Count ); Return Revoke learray [randomint];} Public override  People Changesomeonename ( People P) {P. Name = "123" ; Return P ;} Public override void Display ( People P ){ Console . Writeline ( "Name :" + P. Name + "\ N" + "Age :" + P. Age );} Private Static int Sortpeople ( People P1, People P2 ){ Return  String . Compare (p1.name, p2.name );}} Public class  People { Private string Name; Private int Age; Public String Name { Get { Return Name ;} Set {Name = Value ;}} Public int Age { Get { Return Age ;}}Public People ( String Name, Int Age ){ This . Name = Name; This . Age = age ;}}

In this way, if we need to modify the sorting method again, does it save a lot of trouble?

Some people may ask at this time what you can think of. Many people may have thought of it! But this is not promoted. Why?

Let's analyze the features of this method:

1. Delegation is actually a type of method template.

2. The original template method is to hide the implementation to the customer. In this way, the implementation is transferred to the customer for implementation. The customer selects the specific implementation of the template.

10. Delegate to the end

Since we all use the delegate "improvement" template method, since we have given the customer the right to implement, we try to increase the right.

In many cases, the customer can select the implementation sequence of the method based on their own. At this time, we can implement the method with delegation.

The method is: we implement some methods in a class exposed to the client, and then we expose these methods to the client, so that the client can assemble these methods according to its own choice. This is actually a good method.

For example, we have a class that implements a lot of encryption algorithms, and then we will use an encryption stream to encrypt the password (note: we will not discuss the decoration mode here ). Then we can let customers choose their own encryption order based on their hobbies and decryption habits.

11. Macro Template Method

The discussion here is done between classes and interfaces. In fact, we can also macro the template method.

In fact, let's think about what the designer and architect are doing? Template method!

They provide us with a software system architecture template, and then let us implement the specific details, that is.

Therefore, we can provide an algorithm template, a system process template, and a software template.

12. Competition

Some friends told me, isn't it a rule of order? This seems like the builder mode.

In fact, they solve two problems:

The template method provides the skeleton of an algorithm.

The builder mode finally assembles an object.

13. Summary

The template method is a simple but important template method, which best explains the power of inheritance.

Some people even say: If you only know one design mode, this mode is the template method mode.

ArticleSo far, I would like to thank you for your attention. I also hope you will give me more advice and comments. I will make corrections so that you can do better and better.

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.