PHP Design Pattern Template Method Pattern Definition and Usage Detailed Explanation

  • 2021-09-16 06:25:28
  • OfStack

This paper illustrates the template method pattern definition and usage of PHP design pattern. Share it for your reference, as follows:

What is a template method pattern

The template method (Template Method) design pattern uses a class method templateMethod (), which is a concrete method in an abstract class. The function of this method is to sort the sequence of abstract methods, and the concrete implementation is left to the concrete class. The key is that the template method pattern defines the "skeleton" of the algorithm in operation, which is implemented by the concrete class.

When to use the template method

If you have identified a few steps in the algorithm, However, these steps can be implemented in many different ways, You can use the template method to debug. If the steps in the algorithm remain the same, you can leave them to the subclasses to implement them. In this case, you can use the template method design pattern to organize the basic operations (functions/methods) in the abstract class. The subclasses then implement the operations required for the application.

Another usage is slightly more complicated, and it may be necessary to put the common behavior of subclasses in one class to avoid code duplication.

If you use multiple classes to solve the same large problem, duplicate code may occur soon.

Another point is that you can use the template method pattern to control subclass extension, which is called "hook".

Example

In PHP programming, you may often encounter a problem: to create an image with graph questions. This algorithm is quite simple, that is, to display the image, and then display the text under the image.

Since only two participants are involved in template design, this is one of the easiest patterns to understand, and it is also very useful. Abstract establishment templateMethod() And the concrete class implements this method.

Abstract class

Abstract classes are the key here because they contain both concrete and abstract methods. Template methods are often concrete methods whose operations are abstract

The two abstract methods are addPicture and addTitile, both of which contain one parameter, representing the URL information of the image and the image title, respectively.

Template.php


<?php
abstract class Template
{
  protected $picture;
  protected $title;
  public function display($pictureNow, $titleNow)
  {
    $this->picture = $pictureNow;
    $this->title = $titleNow;
    $this->addPicture($this->picture);
    $this->addTitle($this->title);
  }
  abstract protected function addPicture($picture);
  abstract protected function addTitle($title);
}

Specific class

Concrete.php


<?php
include_once('Template.php');
class Concrete extends Template
{
  protected function addPicture($picture)
  {
    $this->picture = 'picture/' . $picture;
    echo " The image path is :" . $this->picture . '<br />';
  }
  protected function addTitle($title)
  {
    $this->title = $title;
    echo "<em> Title : </em>" . $this->title . "<br />";
  }
}

Customer

Client.php


<?php
function __autoload($class_name)
{
  include $class_name . '.php';
}
class Client
{
  public function __construct()
  {
    $title = "chenqionghe is a handsome boy";
    $concrete = new Concrete();
    $concrete->display('chenqionghe.png', $title);
  }
}
$worker = new Client();

The $concrete variable instantiates Concrete, but it calls the display template method, which is a concrete operation inherited from the parent class, which passes through the display() Calls the operation of the subclass.

Output after running

Image path: picture/chenqionghe. png
Title: chenqionghe is a handsome boy

As you can see, the customer only needs to provide the image address and title

Hook in Template Method Design Pattern

Sometimes a template method function may have a step that you don't want, and you may not want to perform this step in some specific situations, so you can use the hook of the template method.

In the template method design pattern, With hooks, you can use 1 method as 1 part of a template, However, this method will definitely be used. In other words, It is part 1 of the method, but it contains a hook that handles exceptions. A subclass can add an optional element to the algorithm so that while still executing in the order in which the template method was created, it may not perform the desired actions of the template method. For this optional case, the hook is the ideal tool for solving this problem.

Example

If you go online to buy goods, you will get a 20% discount. If the total cost of goods exceeds that of 200 yuan, you will be exempted from the freight of 12.95 yuan.

Create a hook

It is interesting to create hook methods in template methods, and although subclasses can change the behavior of hooks, they still follow the order defined in the template

IHook.php


<?php
abstract class IHook
{
  protected $hook;
  protected $fullCost;
  public function templateMethod($fullCost, $hook)
  {
    $this->fullCost = $fullCost;
    $this->hook = $hook;
    $this->addGoods();
    $this->addShippingHook();
    $this->displayCost();
  }
  protected abstract function addGoods();
  protected abstract function addShippingHook();
  protected abstract function displayCost();
}

There are three abstract methods: addGoods() , addShippingHook() , displayCost() Object implemented by the abstract class IHook templateMethod() Here, the hook method is placed in the middle, and in fact, the hooks can be placed anywhere in the order specified by the template method. The template method requires two parameters, one is the total cost, and one variable is needed to determine whether the customer is free of freight.

Implement hook

1 Once these abstract methods are established in the abstract class and the order in which they are executed is specified, the subclass will implement all three methods:

Concrete.php


<?php
class Concrete extends IHook
{
  protected function addGoods()
  {
    $this->fullCost = $this->fullCost * 0.8;
  }
  protected function addShippingHook()
  {
    if(!$this->hook)
    {
      $this->fullCost += 12.95;
    }
  }
  protected function displayCost()
  {
    echo " You need to pay : " . $this->fullCost . ' Yuan <br />';
  }
}

addGoods and displayCost are both standard methods, with only one implementation. However, the implementation of addShippingHook is different, in which there is one condition to determine whether to increase freight. This is the hook.

Customer Client

Client.php


<?php
function __autoload($class_name)
{
  include $class_name . '.php';
}
class Client
{
  private $totalCost;
  private $hook;
  public function __construct($goodsTotal)
  {
    $this->totalCost = $goodsTotal;
    $this->hook = $this->totalCost >= 200;
    $concrete = new Concrete();
    $concrete->templateMethod($this->totalCost, $this->hook);
  }
}
$worker = new Client(100);
$worker = new Client(200);

The Client demonstrates the final cost of purchasing 100 yuan and 200 yuan goods respectively, and the running results are as follows

You need to pay: 92.95 yuan
You need to pay: 160 yuan

For more readers interested in PHP related content, please check the topics on this site: "Introduction to php Object-Oriented Programming", "Introduction to PHP Basic Syntax", "Encyclopedia of PHP Array (Array) Operation Skills", "Summary of php String (string) Usage", "Introduction to php+mysql Database Operation" and "Summary of php Common Database Operation Skills"

I hope this paper is helpful to everyone's PHP programming.


Related articles: