责任链模式

责任链模式将处理请求的对象连成一条链,沿着这条链传递该请求,直到有一个对象处理请求为止,这使得多个对象都有机会处理请求,从而避免请求的发送者和接受者之间的耦合关系。
责任链模式在现实中使用的很多,常见的就是 OA 系统中的工作流。

责任链模式的主要优点在于可以降低系统的耦合度,简化对象的相互连接,同时增强给对象指派职责的灵活性,增加新的请求处理类也很方便;
其主要缺点在于不能保证请求一定被接收,且对于比较长的职责链,请求的处理可能涉及到多个处理对象,系统性能将受到一定影响,而且在进行代码调试时不太方便。

 

 1 <?php
 2 
 3 /**
 4  * 我们创建抽象类 AbstractLogger,带有详细的日志记录级别。然后我们创建三种类型的记录器,都扩展了 AbstractLogger。
 5  * 每个记录器消息的级别是否属于自己的级别,如果是则相应地打印出来,否则将不打印并把消息传给下一个记录器。
 6  */
 7 
 8 abstract class AbstractLogger
 9 {
10     public static $info = 1;
11     public static $debug = 2;
12     public static $error = 3;
13 
14     protected $_level;
15     protected $_nextLogger;             //important concept
16 
17 
18     public function setNextLogger(AbstractLogger $abstractLogger)
19     {
20         $this->_nextLogger = $abstractLogger;
21     }
22 
23     public function logMessage($level, $message)
24     {
25         if ($this->_level == $level) {
26             $this->write($message);
27         }
28 
29         if ($this->_nextLogger) {
30             $this->_nextLogger->logMessage($level, $message);
31         }
32     }
33 
34 
35     abstract protected function write($msg);
36 }
37 
38 
39 
40 class ConsoleLogger extends AbstractLogger
41 {
42     public function __construct($level)
43     {
44         $this->_level = $level;
45     }
46 
47     protected function write($msg)
48     {
49         echo "<br/>Standard Console::Logger: ".$msg;
50     }
51 }
52 
53 class ErrorLogger extends AbstractLogger
54 {
55     public function __construct($level)
56     {
57         $this->_level = $level;
58     }
59 
60     protected function write($msg)
61     {
62         echo "<br/>Error Console::Logger: ".$msg;
63     }
64 }
65 
66 class FileLogger extends AbstractLogger
67 {
68     public function __construct($level)
69     {
70         $this->_level = $level;
71     }
72 
73     protected function write($msg)
74     {
75         echo "<br/>File Console::Logger: ".$msg;
76     }
77 }
78 
79 
80 
81 
82 $errorLogger = new ErrorLogger(AbstractLogger::$error);
83 $fileLogger = new FileLogger(AbstractLogger::$debug);
84 $consoleLogger = new ConsoleLogger(AbstractLogger::$info);
85 
86 $consoleLogger->setNextLogger($fileLogger);
87 $fileLogger->setNextLogger($errorLogger);
88 
89 $chain = $consoleLogger;
90 
91 
92 $chain->logMessage(AbstractLogger::$info, "This is an information.");
93 $chain->logMessage(AbstractLogger::$debug, "This is an debug level information.");
94 $chain->logMessage(AbstractLogger::$error, "This is an error information.");
View Code
原文地址:https://www.cnblogs.com/hangtt/p/6264341.html