责任链模式

类图

2024072123224754.png

代码

<?php
 
// 定义一个抽象处理者类
abstract class Handler
{
private $nextHandler;
 
public function setNext(Handler $handler): Handler
{
$this->nextHandler = $handler;
return $handler;
}
 
public function handle(Request $request): void
{
if ($this->nextHandler) {
$this->nextHandler->handle($request);
}
}
}
 
// 定义一个具体处理者类 A
class ConcreteHandlerA extends Handler
{
public function handle(Request $request): void
{
if ($request->getRequestType() === 'TypeA') {
echo "ConcreteHandlerA 处理请求\n";
} else {
parent::handle($request);
}
}
}
 
// 定义一个具体处理者类 B
class ConcreteHandlerB extends Handler
{
public function handle(Request $request): void
{
if ($request->getRequestType() === 'TypeB') {
echo "ConcreteHandlerB 处理请求\n";
} else {
parent::handle($request);
}
}
}
 
// 定义请求类
class Request
{
private $requestType;
 
public function __construct(string $type)
{
$this->requestType = $type;
}
 
public function getRequestType(): string
{
return $this->requestType;
}
}
 
// 客户端代码
$requestA = new Request('TypeA');
$requestB = new Request('TypeB');
$requestC = new Request('TypeC');
 
$handlerA = new ConcreteHandlerA();
$handlerB = new ConcreteHandlerB();
 
$handlerA->setNext($handlerB);
 
echo "处理 RequestA:\n";
$handlerA->handle($requestA);
 
echo "\n处理 RequestB:\n";
$handlerA->handle($requestB);
 
echo "\n处理 RequestC:\n";
$handlerA->handle($requestC);