设计模式之责任链


定义子类
首先定义三个类,要声明power权值,以power来判断是否有权利去操作,传过来的数据,还需要声明上一级,责任链模式,要有层级关系

class Banzhu extends Admin
{
   protected $power = 1;
   protected $top = 'Police';

   public function doProc() {
       echo '删帖';
   }
}

class Police extends Admin
{
   protected $power = 2;
   protected $top = 'Guoan';

   public function doProc() {
       echo '抓人';
   }
}

class Guoan extends Admin
{
   protected $power = 3;
   protected $top = null;

   public function doProc() {
       echo '灭口';
   }
}

定义父类
子类均要继承父类方法Admin,Admin的__construct构造方法中,首先判断该类的上一级是否为空,如果是,那么该类是这个责任链中的顶级。

class Admin
{
  public function __construct() {
      if ($this->top == null) {
          return;
      }
      $this->toper = new $this->top();
  }

  public function proc($danger) {
      if($danger <= $this->power) {
          $this->doProc();
      } else {
          $this->toper->proc($danger);
      }
  }
}

调用
实例化最底层类,然后调用方法传入power

$obj = new Banzhu();
$obj->proc(3);