责任链模式
责任链模式:
请求方发起请求,接收方接受请求,并解决请求方的问题,如果接收方不能解决问题,则将请求传给下一个接收方(上一级),让下一个接收方来解决问题,以此类推,发起请求方并不关心是谁解决了问题,只关心是否解决了问题。
<?php class Admin{ public $top=""; public $level=0; public function __construct(){ } public function ToDo(){} public function deal($level){ if($level <= $this->level){ //如果当前类能够解决问题,则直接让当前类解决,不用传递给上级 $this->ToDo(); } else { //如果当前类的等级不够(不能解决问题),则将问题传递给上一级 //即生成一个上级类,然后调用上级类的方法来解决问题,层层深入,直到解决问题 //top属性初始为上级类名 //将新生成的上级类的实例化对象赋给top属性 $this->top= new $this->top; $this->top->deal($level); } } } class PersonOne extends Admin{ public $level=1; public $top="PersonTwo"; public function ToDo(){ echo "the problem has been solved by PersonOne\n"; } } class PersonTwo extends Admin{ public $level=2; public $top="PersonThree"; public function ToDo(){ echo "the problem has been solved by PersonTwo\n"; } } class PersonThree extends Admin{ public $level=3; public $top=__CLASS__; public function ToDo(){ echo "the problem has been solved by PersonThree\n"; } } $level=1; $d=new PersonOne(); $d->deal($level); $level=2; $d=new PersonOne(); $d->deal($level); $level=3; $d=new PersonOne(); $d->deal($level); ?>
参考 责任链 | 菜鸟教程 http://www.runoob.com/design-pattern/chain-of-responsibility-pattern.html
如需转载,请注明文章出处,谢谢!!!