技术成就梦想

代码如诗

原 责任链模式 eatnothing

2017年8月31日 未分类 0

责任链模式

使多个对象有机会处理请求,从而避免了请求者和发送者的耦合关系,将这些对象连城一条链,并沿着这条链传递请求,直到有人处理它

#####组成

  • 请求者(也可以有抽象类)
  • 抽象管理者
  • 实体管理者(>2)
<?php

/**
 * User: didi
 * Date: 2017/8/31
 * Time: 下午5:20
 */
class Request {
    public $name;
    public $num;
}


abstract class  Manager {
    protected $name;
    protected $manager;

    public function __construct($_name){
        $this->name = $_name;
    }


    public function setManager(Manager $manager){
        $this->manager = $manager;
    }

    abstract function apply(Request $request);
}


class Father extends Manager {
    public function __construct($name){
        parent::__construct($name);
    }

    public function apply(Request $request){


        if ($request->num != 5) {
            echo 'this is not 5';
        } else {
            $this->manager->apply($request);
        }

    }
}

class GrandFather extends Manager {
    public function __construct($name){
        parent::__construct($name);
    }

    public function apply(Request $request){
        
        echo 'fuck this is ur grandFather';

    }
}


class Client {


    public function __construct(){
        $re = new Request();
        $re->num = 5;
        $father  = new Father('fucker');
        $grand_father = new GrandFather('mother');

        $father->setManager($grand_father);


        $father->apply($re);

    }
}


$a = new Client();