Home >Backend Development >PHP Tutorial >Php design patterns: behavioral patterns (3)

Php design patterns: behavioral patterns (3)

巴扎黑
巴扎黑Original
2016-11-12 11:53:03852browse

7. Chain of Responsibility:

Multiple objects have the opportunity to process requests, decoupling the request sender and receiver. Just like a cash machine in a bank, you can withdraw money from any machine.

Benefits: Simplify the object hidden chain structure, making it easy to add new responsibility nodes.

Disadvantages: The request may have no receiver, or be called by multiple receivers, resulting in reduced performance.

Application scenario: Handle multiple requests.

Code implementation:

<?php
/**
 * 优才网公开课示例代码
 *
 * 职责链模式 Chain of Responsibility
 *
 * @author 优才网全栈工程师教研组
 * @see http://www.ucai.cn
 */
function output($string) {
    echo    $string . "\n";
}
/** 
 * 加入在公司里,如果你的请假时间小于0.5天,那么只需要向leader打声招呼就OK了。 
  如果0.5<=请假天数<=3天,需要先leader打声招呼,然后部门经理签字。 
  如果3<请假天数,需要先leader打声招呼,然后到部门经理签字,最后总经经理确认签字, 
    如果请假天数超过10天,是任何人都不能批准的。
 */ 
  
/** 
 * 抽象处理者角色(Handler:Approver):定义一个处理请求的接口,和一个后继连接(可选) 
 * 
 */  
abstract class Handler 
{  
    protected $_handler = null;  
    protected $_handlerName = null;  
      
    public function setSuccessor($handler)  
    {  
        $this->_handler = $handler;  
    }  
      
    protected  function _success($request)  
    {  
        output(sprintf("%s&#39;s request was passed", $request->getName())); 
        return true;  
    }  
    abstract function handleRequest($request);  
}  
/** 
 * 具体处理者角色(ConcreteHandler:President):处理它所负责的请求,可以访问后继者,如果可以处理请求则处理,否则将该请求转给他的后继者。 
 * 
 */  
class ConcreteHandlerLeader extends Handler  
{  
    function __construct($handlerName){  
        $this->_handlerName = $handlerName;  
    }  
    public function handleRequest($request)  
    {  
        if($request->getDay() < 0.5) {  
            output(sprintf(&#39;%s was told&#39;, $this->_handlerName));       // 已经跟leader招呼了
            return $this->_success($request);  
        }   
        if ($this->_handler instanceof Handler) {  
            return $this->_handler->handleRequest($request);  
        }  
    }  
}  
/** 
 * Manager 
 * 
 */  
class ConcreteHandlerManager extends Handler  
{  
    function __construct($handlerName){  
        $this->_handlerName = $handlerName;  
    }  
      
    public function handleRequest($request)  
    {  
        if(0.5 <= $request->getDay() && $request->getDay()<=3) {  
            output(sprintf(&#39;%s signed&#39;, $this->_handlerName));       // 部门经理签字
            return $this->_success($request);  
        }   
        if ($this->_handler instanceof Handler) {  
            return $this->_handler->handleRequest($request);  
        }  
    }  
}  
class ConcreteHandlerGeneralManager extends Handler  
{  
    function __construct($handlerName){  
        $this->_handlerName = $handlerName;  
    }  
      
    public function handleRequest($request)  
    {  
        if(3 < $request->getDay() && $request->getDay() < 10){  
            output(sprintf(&#39;%s signed&#39;, $this->_handlerName));       // 总经理签字
            return $this->_success($request);  
        }  
        if ($this->_handler instanceof Handler) {  
            return $this->_handler->handleRequest($request);  
        } else {
            output(sprintf(&#39;no one can approve request more than 10 days&#39;));
        }
    }  
}  
/** 
 * 请假申请 
 * 
 */  
class Request  
{  
    private $_name;  
    private $_day;  
    private $_reason;  
  
    function __construct($name= &#39;&#39;, $day= 0, $reason = &#39;&#39;){  
        $this->_name = $name;  
        $this->_day = $day;  
        $this->_reason = $reason;  
    }  
      
    public function setName($name){  
        $this->_name = $name;  
    }  
    public function getName(){  
        return  $this->_name;  
    }  
      
    public function setDay($day){  
        $this->_day = $day;  
    }  
    public function getDay(){  
        return  $this->_day ;  
    }  
      
    public function setReason($reason ){  
         $this->_reason = $reason;  
    }  
    public function getReason( ){  
        return  $this->_reason;  
    }  
}  
  
  
class Client {  
      
    public static function test(){  
          
        $leader = new ConcreteHandlerLeader(&#39;leader&#39;);  
        $manager = new ConcreteHandlerManager(&#39;manager&#39;);  
        $generalManager = new ConcreteHandlerGeneralManager(&#39;generalManager&#39;);  
          
        //请求实例  
        $request = new Request(&#39;ucai&#39;,4,&#39;休息&#39;);  
          
        $leader->setSuccessor($manager);  
        $manager->setSuccessor($generalManager);  
        $result =  $leader->handleRequest($request);  
    }  
      
}  
  
Client::test();

8. Strategy pattern:

Define a series of algorithms, encapsulate each algorithm, and make them interchangeable. Just like the players on a basketball team, on and off the court. The coach can let those on the field come down, and he can also let those off the field play.

Benefits: Define a series of reusable algorithms and behaviors, and eliminate if else statements.

Disadvantage: The calling end must know all strategy classes.

Application scenario: Used for replacement between objects.

Code implementation:

<?php
/**
 * 优才网公开课示例代码
 *
 * 策略模式 Strategy
 *
 * @author 优才网全栈工程师教研组
 * @see http://www.ucai.cn
 */
function output($string) {
    echo    $string . "\n";
}
//策略基类接口
interface IStrategy {
    public function OnTheWay();
}
class WalkStrategy implements IStrategy {
    public function OnTheWay() {
        output( &#39;在路上步行&#39;);
    }
}
class RideBickStrategy implements IStrategy {
    public function OnTheWay() {
        output( &#39;在路上骑自行车&#39;);
    }
}
class CarStrategy implements IStrategy {
    public function OnTheWay() {
        output( &#39;在路上开车&#39;);
    }
}
//选择策略类Context
class Context {
    public function find($strategy) {
        $strategy->OnTheWay();
    }
}
class Client {  
      
    public static function test(){  
        $travel = new Context();
        $travel->find(new WalkStrategy());
        $travel->find(new RideBickStrategy());
        $travel->find(new CarStrategy());
    }  
      
}  
  
Client::test();

Known modes

1. Memento mode (Memento):

Save the state of the object at a moment. Dear, do you still remember that deskmate who said, "Please call me when the teacher is here"?

Benefits: Provides users with a mechanism to restore their status.

Disadvantages: Consumption of resources.

Application scenario: used for data that needs to be saved.

Code implementation:

<?php
/**
 * 优才网公开课示例代码
 *
 * 备忘录模式 Memento
 *
 * @author 优才网全栈工程师教研组
 * @see http://www.ucai.cn
 */
function output($string) {
    echo    $string . "\n";
}
class Originator { // 发起人(Originator)角色
    private $_state;
    public function __construct() {
        $this->_state = &#39;&#39;;
    }
    public function createMemento() { // 创建备忘录
        return new Memento($this->_state);
    }
    public function restoreMemento(Memento $memento) { // 将发起人恢复到备忘录对象记录的状态上
        $this->_state = $memento->getState();
    }
    public function setState($state) { $this->_state = $state; } 
    public function getState() { return $this->_state; }
    public function showState() {
        output($this->_state);
    }
}
class Memento { // 备忘录(Memento)角色 
    private $_state;
    public function __construct($state) {
        $this->setState($state);
    }
    public function getState() { return $this->_state; } 
    public function setState($state) { $this->_state = $state;}
}
class Caretaker { // 负责人(Caretaker)角色 
    private $_memento;
    public function getMemento() { return $this->_memento; } 
    public function setMemento(Memento $memento) { $this->_memento = $memento; }
}
class Client {  
      
    public static function test(){  
        $org = new Originator();
        $org->setState(&#39;open&#39;);
        $org->showState();
        /* 创建备忘 */
        $memento = $org->createMemento();
        /* 通过Caretaker保存此备忘 */
        $caretaker = new Caretaker();
        $caretaker->setMemento($memento);
        /* 改变目标对象的状态 */
        $org->setState(&#39;close&#39;);
        $org->showState();
        /* 还原操作 */
        $org->restoreMemento($caretaker->getMemento());
        $org->showState();
    }  
      
}  
  
Client::test(); 
return;
try {
    $db->beginTransaction();
    $succ   = $db->exec($sql_1);
    if (!$succ) {
        throw new Exception(&#39;SQL 1 update failed&#39;);
    }
    $succ   = $db->exec($sql_2);
    if (!$succ) {
        throw new Exception(&#39;SQL 2 update failed&#39;);
    }
    $succ   = $db->exec($sql_3);
    if (!$succ) {
        throw new Exception(&#39;SQL 3 update failed&#39;);
    }
    $db->commit();
} catch (Exception $exp) {
    $db->rollBack();
}

Deep mode

1. Interpreter mode (Interpreter):

Define the grammar of the language and build an interpreter to interpret sentences in the language. Every kid who has used a dictionary knows this.

Advantages: Good scalability and flexibility.

Disadvantages: It may be difficult to maintain complex grammars.

Application scenario: Used for pair or one-to-many requirements.

2. Visitor mode:

Encapsulates certain operations that act on each element in a certain data structure. You can define new operations that act on these elements without changing the data structure. Such as bank numbering machine.

Benefits: Concentrate related things into a visitor object.

Disadvantages: It is difficult to add new data structures.

Application scenarios: Queuing, numbering.

3. Summary

This article introduces behavioral patterns. Behavioral patterns involve the allocation between algorithms and object responsibilities. Behavioral class patterns use inheritance mechanisms to assign behaviors between classes. TemplateMethod and Interpreter are class behavior patterns. . Behavioral object patterns use object composition instead of inheritance. Some behavioral object patterns describe how a group of peer objects cooperate with each other to complete tasks that no one object can complete alone. For example, Mediator introduces a mediator object between objects to provide Indirectness required for loose coupling; Chain of Responsibility provides looser coupling. It implicitly sends a loose request to an object through a candidate object chain, and can determine which candidates participate in the chain at runtime; Observer defines and maintains Dependencies between objects; other behavioral object patterns often encapsulate behavior in an object and assign requests to it. Strategy pattern encapsulates algorithms in objects, so that aspects can be changed and specified by an object. Algorithm; Command mode encapsulates the request in an object so that it can be passed as a parameter and can be stored in a history list or used in other ways; State mode encapsulates the state of an object so that when the object's state object changes , the object can change its behavior; the Visitor pattern encapsulates the behavior distributed among multiple classes; and the Iterator pattern abstracts the way to access and traverse objects in a collection.


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn