Design Pattern 19: template method pattern (template method pattern)

Source: Internet
Author: User
Tags what inheritance

Define: Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. template method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.

1. template method mode

Prepare an abstract class, implement part of the logic in the form of a specific method and a specific constructor, and then declare some abstract methods to force the subclass to implement the remaining logic. Different sub-classes can implement these abstract methods in different ways to implement the rest logic differently. This is the intention of the template method mode.

Many people may not think that the template method mode is actually one of the most common modes in all modes, and many may have used the template method mode without realizing that they have already used this mode. The template method mode is a basic technology based on inherited code reuse. The structure and usage of the template method mode is also the core of object-oriented design.

The template method mode requires collaboration between designers who develop abstract classes and specific sub-classes. One designer is responsible for providing the outline and skeleton of an algorithm, while other designers are responsible for providing the logical steps of this algorithm. The method representing these specific logical steps is called the basic method. The method that aggregates these basic methods is called the template method ), the name of this design pattern is from here.

Ii. Structure of the template method mode

Shows the static structure of the template method mode.

 

Two roles are involved:

  • The role of abstractclass has the following responsibilities:

Defines one or more abstract operations to implement sub-classes. These abstract operations are called basic operations, which constitute a step of top-level logic.

Defines and implements a template method. This template method is generally a specific method, which provides a skeleton of top-level logic, and the logical composition steps are postponed to subclass implementation in the corresponding abstract operations. The top-level logic may also call some specific methods.

  • The role of a specific template (concreteclass) has the following responsibilities:

Implement one or more abstract methods defined by the parent class. They constitute a step of top-level logic.

Each abstract template role can have any number of specific template roles, and each specific template role can provide these abstract methods (that is, the composition steps of top-level Logic) so that the implementation of the top-level logic is different.

Iii. Schematic code of template method mode Using system; <br/> using system. collections. generic; <br/> using system. LINQ; <br/> using system. text; </P> <p> namespace template_method_pattern <br/> {<br/> // "abstractclass" <br/> abstract class abstractclass <br/> {<br/>/ /methods <br/> Abstract Public void primitiveoperation1 (); <br/> Abstract Public void primitiveoperation2 (); </P> <p> // The template method <br/> Public void templatemethod () <br/> {<br/> console. writeline ("in abstractclass. templatemethod () "); <br/> primitiveoperation1 (); <br/> primitiveoperation2 (); <br/>}</P> <p> // "concreteclass" <br/> class concreteclass: abstractclass <br/>{< br/> // methods <br/> Public override void primitiveoperation1 () <br/>{< br/> console. writeline ("called concreteclass. primitiveoperation1 () "); <br/>}</P> <p> Public override void primitiveoperation2 () <br/>{< br/> console. writeline ("called concreteclass. primitiveoperation2 ()"); <br/>}</P> <p>/**/<br/> /// <summary> <br/> // client Test <br/> // </Summary> <br/> public class client <br/> {<br/> Public static void main (string [] ARGs) <br/>{< br/> // create instance and call template method <br/> concreteclass c = new concreteclass (); <br/> C. templatemethod (); </P> <p> console. read (); <br/>}< br/>
Iv. inheritance as a reusable Tool

Exercise caution when using inheritance as a means of reuse. Designers of C # have different levels of knowledge about using inheritance as a tool for reuse.

I do not know

First, programmers who are new to C # may not know what inheritance is or think that "inheritance" is an advanced tool. At that time, most of the functions were reused through delegation.

I do not know ii

Then, they gradually discovered that it was not difficult to implement inheritance in the C # language, and initially realized that inheritance could make the subclass suddenly get the behavior of the base class. At this time, they will be eager to try, try to use inheritance as the main tool for Functional Reuse, and change the original place where the delegate should be used to use inheritance, then there is a danger of misuse of inheritance.

Zhi er

Many object-oriented design experts have warned about the possibility of misuse of inheritance relationships since 1986. Some object-oriented programming languages, such as the Self language, have even removed the class inheritance relationship from the language function and changed it to full use of delegation.

Although other designers do not advocate the full cancellation of inheritance, they encourage them to try to replace the inherited relationship with the delegated relationship as much as possible in the design. For example, in the book gof95, the State mode, policy mode, decoration mode, bridge mode, and abstract factory mode convert the inherited implementation into object-based combination and aggregation, the main point of these modes is to replace the inheritance relationship with the delegate relationship.

Zhi 3

Shouldn't inheritance be used at all? In fact, the abstraction, inheritance, encapsulation and Polymorphism of data are also called the most important features of C # and most other object-oriented languages. Inheritance should not be abused. It does not mean that inheritance should not be used at all. Because inheritance is easy to abuse, it is tantamount to abandoning inheritance completely.

Inheritance makes the hierarchical structure of types easy to understand, maintain, and expand. the hierarchical structure of types is very suitable for Abstract Design, Implementation, and reuse. Although the design patterns provided by gof95 are basically not many inheritance-based models, many models are defined and implemented using inheritance methods. Most design patterns describe a hierarchical structure that uses abstract classes as the base class and specific classes as implementation, such as the adapter mode, merging mode, bridge mode, and state mode.

The template method mode goes further: This mode encourages proper use of inheritance. This mode can be used to rewrite some related classes with the same functions, move reusable general behavior code to the base class, and move the special behavior code to the subclass.

Therefore, familiarity with the template method mode becomes a good place for re-learning and inheritance.

5. Example of a practical Template Method

The following example demonstrates the template method for database access. Make sure that the ACCESS database nwind. mdb exists in the root directory of the C drive (which can be found in the installation directory of the office. For Chinese users, note that the field names may be different ).

Using system; <br/> using system. collections. generic; <br/> using system. LINQ; <br/> using system. text; <br/> using system. data; <br/> using system. data. oledb; </P> <p> namespace template_method_pattern <br/> {<br/> // "abstractclass" <br/> abstract class dataobject <br/> {<br/>/ /methods <br/> Abstract Public void connect (); <br/> Abstract Public void select (); <br/> Abstract Public void process (); <br/> Abstract Public void disconnect (); </P> <p> // The "template method" <br/> Public void run () <br/>{< br/> connect (); <br/> select (); <br/> process (); <br/> disconnect (); <br/>}</P> <p> // "concreteclass" <br/> class customerdataobject: dataobject <br/> {<br/> private string connectionstring = <br/> "provider = Microsoft. jet. oledb.4.0; "<br/> +" Data Source = C: // nwind. mdb "; <br/> private string commandstring; <br/> private dataset; </P> <p> // methods <br/> Public override void connect () <br/>{< br/> // nothing to do <br/>}</P> <p> Public override void select () <br/>{< br/> commandstring = "select companyName from customers"; <br/> oledbdataadapter dataadapter = new oledbdataadapter (<br/> commandstring, connectionstring ); <br/> dataset = new dataset (); <br/> dataadapter. fill (dataset, "MERs"); <br/>}</P> <p> Public override void process () <br/> {<br/> datatable = dataset. tables ["MERs"]; <br/> foreach (datarow in datatable. rows) <br/> console. writeline (datarow ["companyName"]); <br/>}</P> <p> Public override void disconnect () <br/>{< br/> // nothing to do <br/>}</P> <p>/**/<br/>/ // <summary> <br/> // templatemethodapp test <br/> /// </Summary> <br/> public class templatemethodapp <br/> {<br/> Public static void main (string [] ARGs) <br/>{< br/> customerdataobject c = new customerdataobject (); <br/> C. run (); </P> <p> console. read (); <br/>}< br/>

Vi. Methods in the template method mode

Template methods can be divided into two categories: Template Method and primitive method ).

Template Method

A template method is defined in an abstract class. It combines basic operation methods to form a general algorithm or a general-line method. This template method is generally defined in the abstract class and inherited completely by the subclass without modification.

Basic Method

There are three basic methods: abstract method, concrete method, and Hook method ).

Abstract method: an abstract method is declared by an abstract class and implemented by a specific subclass. In C #, an abstract method is marked with the abstract keyword.

Specific Method: a specific method is declared and implemented by the abstract class, And the subclass is not implemented or replaced. In C #, a specific method does not contain abstract keywords.

Hook method: A hook method is declared and implemented by the abstract class, And the subclass is extended. An abstract class usually provides an empty implementation as the default Implementation of the method. (Projects created by the Project Wizard in Visual Foxpro use an apphook class to monitor changes of project members and adjust the system structure .) The name of the hook method usually starts with do.

VII. Principles of restructuring

When restructuring an inherited hierarchical structure, the principle that should be followed is to move behavior to the high-end structure as much as possible, and move the state to the low-end structure as much as possible.

In 1995, Auer pointed out in the document "auer95:

  1. A class should be defined based on behaviors rather than States. That is to say, the implementation of a class is first based on the behavior, rather than the State.
  2. When implementing behaviors, abstract states are used instead of specific States. If an action involves the object state, indirect references are used instead of direct references. In other words, the value method should be used instead of directly referencing the attribute.
  3. Divide operations into layers. The behavior of a class should be put in the kernel method of A group. These methods can be easily replaced in the subclass.
  4. Postpone the confirmation of the Status attribute to the subclass. Do not declare attribute variables too early in the abstract class, and postpone them to the subclass as much as possible. In an abstract superclass, If you need State attributes, you can call the abstract value method and place the implementation of the abstract value method into a specific subclass.

If you can follow this principle, you can separate the interfaces and implementations in the hierarchy, and separate the abstraction from the specifics to ensure that the code can be reused to the maximum extent. This process actually directs the designer to the 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.