Php 디자인 패턴: 행동 패턴 (3)

巴扎黑
풀어 주다: 2016-11-12 11:53:03
원래의
787명이 탐색했습니다.

7. 책임 사슬:

여러 개체에는 요청을 처리할 수 있는 기회가 있어 요청 보낸 사람과 받는 사람이 분리됩니다. 은행의 현금인출기와 마찬가지로 어느 기계에서든 돈을 인출할 수 있습니다.

이점: 객체 숨겨진 체인 구조가 단순화되어 새로운 책임 노드를 더 쉽게 추가할 수 있습니다.

단점: 요청에 수신자가 없거나 여러 수신자가 호출하여 성능이 저하될 수 있습니다.

애플리케이션 시나리오: 여러 요청을 처리합니다.

코드 구현:

<?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. 전략 모드:

일련의 알고리즘을 정의하고, 각 알고리즘을 캡슐화하고, 상호 교환 가능하게 만듭니다. 코트 안팎에서 농구팀의 선수들처럼요. 코치는 경기장에 있는 사람들을 내려오게 할 수도 있고, 경기장 밖에서 뛰게 할 수도 있습니다.

이점: 재사용 가능한 일련의 알고리즘과 동작을 정의하고 if else 문을 제거합니다.

단점: 호출측은 모든 전략 클래스를 알아야 합니다.

적용 시나리오: 개체 간 교체에 사용됩니다.

코드 구현:

<?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();
로그인 후 복사

알려진 모드

1. 메멘토 모드(Memento):

순간적으로 객체의 상태를 저장합니다. 여러분, "선생님 오시면 전화주세요"라고 했던 그의 동료를 아직도 기억하시나요?

이점: 사용자에게 상태를 복원하는 메커니즘을 제공합니다.

단점: 자원 소모.

적용 시나리오: 저장해야 하는 데이터에 사용됩니다.

코드 구현:

<?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();
}
로그인 후 복사

딥 모드

1. 통역 모드(통역):

언어의 문법을 정의하고 해석을 작성합니다. 기계는 언어로 된 문장을 해석합니다. 사전을 사용해 본 모든 어린이는 이것을 알고 있습니다.

장점: 확장성과 유연성이 좋습니다.

단점: 복잡한 문법은 유지 관리가 어려울 수 있습니다.

적용 시나리오: 쌍 또는 일대다 요구 사항으로 사용됩니다.

2. 방문자 모드(Visitor):

데이터 구조를 변경하지 않고도 각 요소에 대해 작업을 정의할 수 있습니다. 이러한 요소. 은행 번호 매기기 기계와 같은.

장점: 관련 항목을 방문자 개체에 집중합니다.

단점: 새로운 데이터 구조를 추가하는 것이 어렵습니다.

적용 시나리오: 대기열, 번호 매기기.

3. 요약

이 글에서는 행동 패턴에 대해 소개합니다. 행동 패턴은 알고리즘과 객체 간의 책임 분배와 관련이 있습니다. TemplateMethod와 Interpreter는 클래스 동작 패턴입니다. 동작 개체 패턴은 상속 대신 개체 구성을 사용합니다. 일부 동작 개체 패턴은 피어 개체 그룹이 서로 협력하여 한 개체가 단독으로 완료할 수 없는 작업을 완료하는 방법을 설명합니다. 예를 들어 Mediator는 필요한 간접성을 제공하기 위해 개체 간에 중재자 개체를 도입합니다. 느슨한 결합의 경우, 느슨한 결합을 제공하며 후보 객체 체인을 통해 암시적으로 객체에 느슨한 요청을 보내고 관찰자는 객체 간의 종속성을 정의하고 유지합니다. 종종 객체의 동작을 캡슐화하고 요청을 할당합니다. 전략 패턴은 객체에 의해 측면이 변경되고 지정될 수 있도록 객체에 요청을 캡슐화하여 매개변수로 전달될 수 있습니다. 기록 목록에 저장되거나 다른 방식으로 사용될 수 있습니다. 상태 모드는 객체의 상태 객체가 변경될 때 객체의 동작을 변경할 수 있도록 객체의 상태를 캡슐화합니다. 반복자 패턴은 컬렉션의 개체에 액세스하고 탐색하는 방법을 추상화합니다.


관련 라벨:
php
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!