Design Mode (20): Template Method template method mode-Behavior Type

Source: Internet
Author: User

 

1. Overview

 

In the process of object-oriented development, we usually encounter the following problem: We know the key steps required by an algorithm and determine the execution sequence of these steps. However, the specific implementation of some steps is unknown, or the implementation of some steps is related to the specific environment.
Example 1: Banking Process
When a bank handles the business, it generally includes several basic fixed steps:
Queuing for receiving numbers-> handling specific services-> scoring bank staff.
Queuing for receiving numbers is the same as the business logic for scoring bank staff. However, different services are handled. The specific services may be withdrawn, deposited, or transferred.

 

2. Problem

 

How can we ensure that the architecture logic is normally executed without being damaged?

 

3. Solution

 

Template Method: defines the skeleton of an algorithm in an operation, and delays some steps to the subclass. The t template method allows the subclass to redefine certain steps of an algorithm without changing the structure of an algorithm. (Template method pattern: definethe skeleton of an algorithm in an operation, deferring some steps tosubclasses. template methodletssubclasses redefine certain steps of an algorithm the algorithm's structure .)

 

1) The template method mode is a basic technique for reusing inherited code. The structure and usage of the template method mode is also the core of object-oriented design. In the template method mode, the same code can be placed in the parent class, while different methods can be implemented in different subclasses. 2) in the template method mode, we need to prepare an abstract class to implement part of the logic in the form of a specific method and a specific constructor, then, declare some abstract methods to implement the residual logic of sub-classes. 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. The template method mode reflects many important object-oriented ideas and is a frequently used mode.

 

 

4. Applicability

 

The template method is applicable to the following situations:
• 1) Implement the unchanged part of an algorithm at one time and leave the variable behavior to the subclass for implementation.
• 2) common behaviors in each subclass should be extracted and centralized into a common parent class to avoid code duplication. First, identify the differences in the existing code and separate the differences into new operations. Finally, replace these different codes with a template method that calls these new operations.
• 3) control subclass extension. The template method only calls the "Hook" operation at specific points, so that the extension can only be performed at these points.

 

5. Structure

 

 

6. Composition of the Mode

Abstract class: Defines abstract primitive operations. Specific subclass will redefine them to implement an algorithm, implement a template method, and define the skeleton of an algorithm. This template method not only calls primitive operations, but also calls Definitions
Concreteclass: Implements primitive operations to complete steps related to a specific subclass in the algorithm.

7. Effect

 

 

  Advantages of the template method mode:
1) The template method mode formally defines an algorithm in a class, and its sub-classes implement detailed processing.
2) The template method is a basic technology for code reuse. They are particularly important in the class library. they extract the public behavior in the class library.
3) The template method mode leads to a reverse control structure, which is sometimes called the "Hollywood law", that is, "Don't look for us ,, we look for you to "use a parent class to call its subclass operations (rather than the opposite subclass to call its parent class), and add new behaviors through the extension of the subclass, in line with the" open and closed principle"

 

Disadvantages of the template method mode:
Each implementation needs to define a subclass, which leads to an increase in the number of classes, a larger system, a more abstract design, but more in line with the "single responsibility principle ", this improves the cohesion of classes.

 

8. Implementation

 

We use the banking implementation and add the Hook method, so that the customer feels that the service is evaluated.

 

  1. <? PHP
  2. /**
  3. * Template method mode:
  4. *
  5. * @ Author guisu
  6. */
  7. /**
  8. * Abstract class
  9. */
  10. Abstract class abstractbank
  11. {
  12. Private $ _ number;
  13. /**
  14. * Template Method
  15. * A subclass cannot override a method defined as final. This ensures that the sub-class logic is always controlled by the parent class.
  16. *
  17. */
  18. Public final function templatemethodprocess ()
  19. {
  20. $ This-> takenumber ();
  21. $ This-> transact ();
  22. If ($ this-> isevaluatehook ()){
  23. $ This-> evaluatehook ();
  24. }
  25. }
  26. /**
  27. * Basic Method-Specific Method
  28. * Get the number
  29. *
  30. */
  31. Private function takenumber ()
  32. {
  33. Return ++ $ this-> _ number;
  34. }
  35. /**
  36. * // Basic method-abstract Method
  37. *
  38. */
  39. Protected abstract function transact ();
  40. /**
  41. * Basic Method-Hook method
  42. *
  43. */
  44. Protected function evaluatehook (){
  45. Echo 'evaluatehook <br/> ';
  46. }
  47. /**
  48. * Basic Method-Hook method
  49. */
  50. Protected function isevaluatehook (){
  51. Return true;
  52. }
  53. }
  54. /**
  55. * Subclass: Deposit
  56. */
  57. Class concretedeposit extends actbank
  58. {
  59. Public Function transact (){
  60. // Implementation code
  61. Echo 'posit', '<br> ';
  62. }
  63. }
  64. /**
  65. * Subclass: Withdrawal
  66. */
  67. Class concretewithdraw extends abstractbank
  68. {
  69. Public Function transact (){
  70. // Implementation code
  71. Echo 'withdraw', '<br> ';
  72. }
  73. }
  74. /**
  75. * Subclass: Transfer
  76. */
  77. Class concretetrancfer extends actbank
  78. {
  79. Public Function transact (){
  80. // Implementation code
  81. Echo 'trancfer ',' <br> ';
  82. }
  83. }
  84. $ C = new concretetrancfer ();
  85. $ C-> templatemethodprocess ();


 

 

9. Other related models

 

1) Policy mode: The template method uses inheritance to change part of the algorithm. Strategy uses delegation to change the entire algorithm. The template method mode is similar to the policy mode, and sometimes the policy mode can be used to replace the template method mode. The template method mode achieves code reuse through inheritance, while the policy mode uses delegation to centralize uncertain behaviors into an interface and delegate the interface to the main class. Delegation is more flexible than inheritance.

 

10. Mode Extension

 

1) template method mode and control reversal (Hollywood principles) in the template method mode, subclass does not explicitly call the parent class method, instead, it implements some specific business logic by overwriting the parent class. The parent class controls the calls to subclass. This mechanism is called the Hollywood principle. The Hollywood principle is defined: "Don't call us. We will call you (Don't call us, we'll call you )". In Hollywood, after you submit your resume to the performing arts company, you have to go home and wait. The Performing Arts Company has full control over the entire entertainment project. actors can only passively accept the company's poor performance and complete their own performances as needed. The template method mode fully embodies the "Hollywood" principle. The parent class fully controls the sub-class logic. The sub-class does not need to call the parent class, but calls the sub-class through the parent class. The sub-class can implement the variable part of the parent class, but inherits the logic of the parent class and cannot change the business logic.

2) The template method mode complies with the open and closed principles.

 

The intent of the template method mode is to control the top-level logic by the abstract parent class, and postpone the implementation of basic operations to sub-classes. This means to reuse objects by means of inheritance, it also complies with the principle of opening and closing.

The parent class is implemented through the top-level logic by defining and providing a specific method, which is also called the template method. Generally, this template method is the most important method for external objects. In the above example,TemplatemethodprocessThis method is the most important method for external objects. Therefore, it must be public to be called by external objects.

The subclass must inherit the parent class to extend the basic methods of the parent class, but it can also override the methods of the parent class. If the subclass overrides the template method of the parent class and changes the top-level logic of the parent class control, this violates the "open/closed principle ". When using the template method mode, we should always ensure that the subclass has the correct logic. Therefore, the template method should be defined as final. Therefore, the templatemethodprocess method of the abstractclass class should be defined as final.

In the template method mode, the template method of the abstract class should be declared as final. The subclass cannot override a method defined as final. This ensures that the sub-class logic is always controlled by the parent class.

 

3) template method mode and object Encapsulation

 

 

 

Object-oriented features: inheritance, encapsulation, and polymorphism.

Objects have internal and external behaviors. Encapsulation is used to hide information and maintain the integrity of internal data of objects. So that external objects cannot directly access the internal state of an object, but they must be accessed through appropriate methods.

Object Attributes and methods are encapsulated with specified delimiters (public, protected, and private, so that data is not maliciously accessed by external objects and methods are not mistakenly called and exported, which leads to the destruction of object encapsulation.

Reducing the access level of a method, that is, maximizing the visibility of the method is an important encapsulation method. In addition to information hiding, the maximum method visibility can effectively reduce the coupling between classes and the complexity of a class. It can also reduce the number of errors that developers encounter.

A class should only expose externally called methods. All methods that serve the public method should be declared as protected or private. If a method is not publicly available, it must be extended or called by the quilt class. Define it as protected. Otherwise it should be private.

Obviously, the basic operations declared as abstract in the template method mode need to be implemented by the subclass, and they only serve the template method. They should not be made public by abstract classes, so they should be protected.

Therefore, in the template method mode, the abstract method that forces subclass implementation should be declared as protected abstract.

 

4) template method and Hook method (hookmethod)

The abstract class definition method of the template method mode:

 

Template Method:A template method is defined in an abstract class and combines basic operation methods to form a general algorithm or a general-line method. Basic method:The basic method is to implement each step of the algorithm and is part of the template method. The basic method is as follows: Abstract method • concrete method • Hook method: "hook" method and empty method. The implementation of the hook method in the abstract class is empty, is left to the subclass for some optional operations. If a subclass requires some special extra operations, you can implement the Hook method. Of course, you can ignore this because the hook is only a null method in the abstract class. 1) The introduction of the hook method allows the subclass to control the behavior of the parent class. 2) The simplest Hook method is the empty method. You can also define a default implementation in the Hook method. If the subclass does not overwrite the Hook method, the default implementation code of the parent class is executed. 3) a more complex Hook method can be used to constrain other methods. This Hook method usually returns a boolean type, that is, true or false, to determine whether to execute a basic method. The subclass determines whether to call the Hook method.

 

11. Summary and Analysis

 

1) The template method mode is a type of behavior mode. In its structure, there is only an inheritance relationship between classes and no object association relationship. 2) the board method mode is a basic technology based on inherited code reuse. The structure and usage of the template method mode is also one of the core aspects of object-oriented design. In the template method mode, the same code can be placed in the parent class, while different methods can be implemented in different subclasses. 3) in the template method mode, we need to prepare an abstract class to implement part of the logic in the form of a specific method and a specific constructor, then, declare some abstract methods to implement the residual logic of sub-classes. 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. The template method mode reflects many important object-oriented ideas and is a frequently used 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.