zoukankan      html  css  js  c++  java
  • 【php设计模式】责任链模式

      责任链模式为请求创建了一个接收者对象的链。这种模式给予请求的类型,对请求的发送者和接收者进行解耦。这种类型的设计模式属于行为型模式。

      在这种模式中,通常每个接收者都包含对另一个接收者的引用。如果一个对象不能处理该请求,那么它会把相同的请求传给下一个接收者,依此类推。

    <?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} 
    ";
        }
    }
    
    class WarningLogger extends AbstractLog{
        public function write($message){
            echo "Warning info: {$message} 
    ";
        }
    }
    
    class ErrorLogger extends AbstractLog{
        public function write($message){
            echo "Error info: {$message} 
    ";
        }
    }
    
    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,"这是一条致命错误");

    输出

    Warning info: 这是一条警告
    Debug info: 这是一条Debug
    Error info: 这是一条致命错误
  • 相关阅读:
    泛型的模板思想
    GTD:是一种态度
    如何debug android cts
    POJ 3352 无向图边双连通分量,缩点,无重边
    Oracle—用户管理的备份(一)
    Retinex processing for automatic image enhancement 翻译
    myBatis抛出异常Result Maps collection already contains value ...
    xxx cannot be resolved to a type 错误解决方法
    Cannot change version of project facet Dynamic Web Module to 3.0
    mysql JDBC URL格式各个参数详解
  • 原文地址:https://www.cnblogs.com/itsuibi/p/11059625.html
Copyright © 2011-2022 走看看