定义:使多个对象都有机会处理请求,从而避免请求发送者和接受者之间的耦合关系。将这些对象连成一条链,并且连着这条链传递该请求,直到有一个对象处理他为止
代码
<?php
abstract class Handler{
protected $successer;
public function setSuccesser($successer){
$this->successer = $successer;
}
abstract function HandleRequest($request);
}
class NumberHandler extends Handler{
public function HandleRequest($request)
{
if ( !is_numeric($request) ){
$this->successer->HandleRequest($request);
}else{
echo $request."是数字\n";
}
}
}
class StringHandler extends Handler{
public function HandleRequest($request)
{
if ( !is_string($request) ){
$this->successer->HandleRequest($request);
}else{
echo $request."是字符串\n";
}
}
}
class OtherHandler extends Handler{
public function HandleRequest($request)
{
echo $request."其他类型\n";
}
}
$numberObj = new NumberHandler();
$stringObj = new StringHandler();
$otherObj = new OtherHandler();
$numberObj->setSuccesser($stringObj);
$stringObj->setSuccesser($otherObj);
$requests = [new StdO1,"aa",null];
foreach ($requests as $request){
$numberObj->HandleRequest($request);
}
------------------------------
结果:
1是数字
aa是字符串
其他类型
具体事例:laravel的中间件