[Php design patterns] chain of responsibility pattern

 Chain of Responsibility pattern creates a chain recipient object to the request. This type of model given request, to the request sender and receiver decoupling. This type of design pattern belongs behavioral patterns.

 In this mode, each receiver typically contains a reference to another recipient. If an object can not process the request, it will pass the same request to the next recipient, and so on.

<?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, "This is a fatal error");

Export

Warning info: This is a warning 
Debug info : This is a Debug 
Error info : This is a fatal error

 

Guess you like

Origin www.cnblogs.com/itsuibi/p/11059625.html