责任链模式,包含了一些命令对象和一些处理对象,每个处理对象决定它能处理那些命令对象,它也知道应该把自己不能处理的命令对象交下一个处理对象,该模式还描述了往该链添加新的处理对象的方法。
上代码
<?php
//责任链模式
//学生向班长请假
//学生处理不了递交给老师
//如果是请长假需要校长批准,递交给校长
//校长
class Monitor{
protected $level = 1;//当前级别为1
protected $top = 'Teacher';//高一级的处理
public function process($level = 1){
if($level <= $this->level){
echo '向班长请假' . '<br/>';
}else{
(new $this->top)->process($level);
}
}
}
//管理员
class Teacher{
protected $level = 2;//当前级别为2
protected $top = 'police';//高一级的处理
public function process($level = 2){
if($level <= $this->level){
echo '班主任参与' . '<br/>';
}else{
(new $this->top)->process($level);
}
}
}
//校长
class Headmaster{
public function process($level = 3){
echo '校长参与' . '<br/>';
}
}
$level = $_GET['level'] ?? 1;
$student = new Monitor();
$student->process($level);