Home > Article > Backend Development > Detailed explanation of the use of PHP template method pattern
This time I will bring you a detailed explanation of the use of PHP template method mode. What are the precautions when using PHP template method mode. The following is a practical case, let's take a look.
What is the template method pattern
Template MethodDesign pattern A class method templateMethod() is used, which is a concrete method in an abstract class. The function of this method is to sort the sequence of abstract methods, and the specific implementation is left to the concrete class. The key is that the template method pattern defines the algorithm in the operation. The "skeleton" is implemented by concrete classes.
When to use template methods
If some steps in the algorithm have been clarified, However, these steps can be implemented in many different ways, and you can use the template method to debug. If the steps in the algorithm remain unchanged, you can leave these steps to the subclass for specific implementation. In this case, you can use the template method to design the pattern. To organize the basic operations (functions/methods) in the abstract class. Then the subclasses implement these operations required by the application.
There is also a slightly more complicated usage, which may need to put the common behaviors of the subclasses into In a class to avoid code duplication.
If you use multiple classes to solve the same large problem, duplicate code may quickly appear.
One more thing, you can use templates The method pattern controls subclass expansion, which is the so-called "hook".
Example
In PHP programming, you may often encounter a problem: To establish a band Image of the picture title. This algorithm is quite simple, it is to display the image, and then display the text below the image.
Since only two participants are involved in the template design, this is one of the easiest patterns to understand, and at the same time Also very useful. Abstractly create templateMethod()
, and implement this method by a concrete class.
Abstract class
Abstract class is the key here , because it contains both concrete and abstract methods. Template methods are often concrete methods, and their operations are abstract.
The two abstract methods are addPicture and addTitile. Both operations contain a parameter, representing the image respectively. URL information and image title.
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); }
Concrete Class
##Concrete.php
<?php include_once('Template.php'); class Concrete extends Template { protected function addPicture($picture) { $this->picture = 'picture/' . $picture; echo "图像路径为:" . $this->picture . '<br />'; } protected function addTitle($title) { $this->title = $title; echo "<em>标题: </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();$concrete variable instantiates Concrete, but it calls display template method, this is a specific operation inherited from the parent class. The parent class calls the operation of the subclass through
display().
The image path is: picture/chenqionghe.pngAs you can see, the customer only needs to provide the image address and titleTitle: chenqionghe is a handsome boy
Hooks in Template Method Design Pattern
Sometimes the template method function may have a step that you don’t want. In some specific cases, you may not want to perform this step. In this case, You can use the hook of the template method.In the template method design pattern, you can use hooks to make a method a part of the template, but this method may not necessarily be used. In other words, it is part of the method. , but it contains a hook that can handle exceptions. Subclasses can add an optional element to the algorithm. In this way, although it is still executed in the order established by the template method, it may not complete the actions expected by the template method. For In this optional situation, hooks are the most ideal tool to solve this problem.Example
Go shopping online and get a 20% discount. If the total product cost exceeds 200 Yuan, the 12.95 Yuan shipping fee will be waived.Establishing hooks
It is interesting to establish hook methods in template methods. Although subclasses can change the behavior of hooks, Still have to follow the order defined in the templateIHook.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(); }
这里有3个抽象方法: addGoods()
, addShippingHook()
,displayCost()
, 抽象类IHook实现的templateMethod()
中确定了它们的顺序. 在这里, 钩子方法放在中间, 实际上模板方法指定的顺序中, 钩子可以放在任意位置. 模板方法需要两个参数, 一个是总花费, 另外还需要一个变量用来确定顾客是否免收运费.
实现钩子
一旦抽象类中建立了这些抽象方法, 并指定了它们执行的顺序, 子类将实现所有这3个方法:
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 "您需要支付: " . $this->fullCost . '元<br />'; } }
addGoods和displayCost都是标准方法, 只有一个实现., 不过, addShippingHook的实现有所不同, 其中有一个条件来确定是否增加运费. 这就是钩子.
客户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);
该Client演示了分别购买100块钱和200块钱的商品最后的费用,运行结果如下
您需要支付: 92.95元
您需要支付: 160元
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of Detailed explanation of the use of PHP template method pattern. For more information, please follow other related articles on the PHP Chinese website!