<?php
//职责链模式
//顾客类
class Customer {
//菜名
private $orderName;
//get set 方法
public function __set($key, $value) {
$this->$key = $value;
}
public function __get($key) {
if(isset($this->$key)) {
return $this->$key;
} else {
return NULL;
}
}
}
//雇员类
abstract class Employee {
//雇员姓名
protected $name;
//职责链下一环
protected $successor;
public function __construct($name) {
$this->name = $name;
}
//设定职责链下一环
public function setSuccessor(Employee $successor) {
$this->successor = $successor;
}
//处理任务转交任务给下一职责人
public function handleRequest(Customer $customer) {
if(!empty($this->successor)) {
$this->successor->handleRequest($customer);
}
}
}
//服务生
class Server extends Employee {}
//主厨
class Chef extends Employee {
public function handleRequest(Customer $customer) {
//判断是否自己职责所在
if($customer->orderName == '农家小炒肉') {
echo $this->name.'做了'.$customer->orderName.'<br/>';
} else {
//调用父类方法(父类的判断等代码不用重复写)
parent::handleRequest($customer);
}
}
}
//二等厨师
class AssistantChef extends Employee {
public function handleRequest(Customer $customer) {
if($customer->orderName == '酸辣土豆丝') {
echo $this->name.'做了'.$customer->orderName.'<br/>';
} else {
parent::handleRequest($customer);
}
}
}
//实例化雇员
$server = new Server('张三');
$chef = new Chef('李四');
$assistantChef = new AssistantChef('王五');
//定义职责链
$server->setSuccessor($chef);
$chef->setSuccessor($assistantChef);
//实例化顾客类
$customer = new Customer();
//点菜
$customer->orderName = '酸辣土豆丝';
//给服务员(职责链开始)
$server->handleRequest($customer);
$customer->orderName = '农家小炒肉';
$server->handleRequest($customer);
?>
职责链模式(Chain of Responsibility Pattern)
最新推荐文章于 2020-11-06 14:49:06 发布