责任链模式为请求创建了一个接收者对象的链。这种模式给予请求的类型,对请求的发送者和接收者进行解耦。这种类型的设计模式属于行为型模式。
在这种模式中,通常每个接收者都包含对另一个接收者的引用。如果一个对象不能处理该请求,那么它会把相同的请求传给下一个接收者,依此类推。
代码语言:javascript复制<?php
define("WARNING_LEVEL", 1);
define("DEBUG_LEVEL", 2);
define("ERROR_LEVEL", 3);
abstract class AbstractLog{
protected $level;
protected $nextlogger;
public function __construct($level){
$this->level = $level;
}
public function setNextLogger($next_logger){
$this->nextlogger = $next_logger;
}
public function logMessage($level,$message){
if($this->level == $level){
$this->write($message);
}
if($this->nextlogger){
$this->nextlogger->logMessage($level,$message);
}
}
abstract function write($message);
}
class DebuggLogger extends AbstractLog{
public function write($message){
echo "Debug info: {$message} n";
}
}
class WarningLogger extends AbstractLog{
public function write($message){
echo "Warning info: {$message} n";
}
}
class ErrorLogger extends AbstractLog{
public function write($message){
echo "Error info: {$message} n";
}
}
function getChainOfLoggers(){
$warning = new WarningLogger(WARNING_LEVEL);
$debugg = new DebuggLogger(DEBUG_LEVEL);
$error = new ErrorLogger(ERROR_LEVEL);
$warning->setNextLogger($debugg);
$debugg->setNextLogger($error);
return $warning;
}
$chain = getChainOfLoggers();
$chain->logMessage(WARNING_LEVEL,"这是一条警告");
$chain->logMessage(DEBUG_LEVEL,"这是一条Debug");
$chain->logMessage(ERROR_LEVEL,"这是一条致命错误");
输出
代码语言:javascript复制Warning info: 这是一条警告
Debug info: 这是一条Debug
Error info: 这是一条致命错误