Template Method mode: Template Method (converted from a. Net)

Source: Internet
Author: User
Tags what inheritance
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 based on inheritance.CodeThe structure and usage of the template method mode are also the core of object-oriented design.

The template method mode requires collaboration between designers who develop abstract classes and specific sub-classes. A designer is responsible for providingAlgorithmAnd other designers are responsible for providing the logic 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

Copy Save
 // Template method pattern -- Structural example  Using System; // "Abstractclass"  Abstract   Class Abstractclass { // Methods    Abstract   Public   Void Primitiveoperation1 (); Abstract   Public   Void Primitiveoperation2 (); // The Template Method    Public   Void Templatemethod () {console. writeline ( "In abstractclass. templatemethod ()" ); Primitiveoperation1 (); primitiveoperation2 ();}} // "Concreteclass"  Class Concreteclass: abstractclass {// Methods    Public   Override   Void Primitiveoperation1 () {console. writeline ( "Called concreteclass. primitiveoperation1 ()" );} Public   Override   Void Primitiveoperation2 () {console. writeline ( "Called concreteclass. primitiveoperation2 ()" );}} /**/ /// <Summary> /// Client Test  /// </Summary>  Public   Class Client { Public   Static   Void Main (String [] ARGs ){ // Create instance and call Template Method Concreteclass c = New Concreteclass (); C. templatemethod ();}}

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, C # beginnersProgramMembers may not know what inheritance is or think that "inheritance" is a profound 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. There are some object-orientedProgramming Language, Such as the Self language, and even removes the class inheritance from the language function, instead of using delegation completely.

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 ).

CopySave

 // Template method pattern -- real world example  Using System; Using System. Data;Using System. Data. oledb; // "Abstractclass"  Abstract   Class Dataobject { // Methods    Abstract   Public   Void Connect (); Abstract   Public   Void Select (); Abstract   Public   Void Process (); Abstract   Public   Void Disconnect (); // The "template method"    Public   Void Run () {connect (); select (); process (); disconnect ();}} // "Concreteclass"  Class Customerdataobject: dataobject { Private   String Connectionstring = "Provider = Microsoft. Jet. oledb.4.0 ;" + "Data Source = C :\\ nwind. mdb" ; Private   String Commandstring; Private Dataset dataset; // Methods    Public   Override   Void Connect (){ // Nothing to do } Public  Override   Void Select () {commandstring = "Select companyName from MERs" ; Oledbdataadapter dataadapter = New Oledbdataadapter (commandstring, connectionstring); dataset = New Dataset (); dataadapter. Fill (dataset, "MERs" );} Public   Override   Void Process () {datatable = dataset. Tables [ "MERs" ]; Foreach (Datarow In Datatable. Rows) console. writeline (datarow [ "CompanyName" ]);}Public   Override   Void Disconnect (){ // Nothing to do }} /**/ /// <Summary> /// Templatemethodapp Test  /// </Summary>  Public   Class Templatemethodapp { Public   Static   Void Main ( String [] ARGs) {customerdataobject c = New Customerdataobject (); C. Run ();}}

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 an abstract class, but not implemented or replaced by a subclass. 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:

define a Class 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.
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.
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.
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 this principle can be followed, interfaces and implementations can be separated in the hierarchy to separate abstraction and specifics, so that 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.