这种模式避免请求的发送者和接收者之间的耦合,通过给超过一个对象一个机会来处理请求。
它链接所有接收者对象并将请求沿着链到一个对象处理它
ConcreteHandler2:(具体处理器2)
This class (a) handles requests it is responsible for, (b) can access its successor, and (c) if it can handle the request, does so, else it forwards it to its successor.
这类(a)处理它负责的请求,(b)可以访问其继任者,(c)如果它可以处理请求,这样做,否则它将其转发给它的继任者。
ConcreteHandler1:(具体处理器1)
This class (a) handles requests it is responsible for, (b) can access its successor, and (c) if it can handle the request, does so, else it forwards it to its successor.
这类(a)处理它负责的请求,(b)可以访问其继任者,(c)如果它可以处理请求,这样做,否则它将其转发给它的继任者。
Handler:(处理器)
This class defines an interface for handling requests and optionally implements the successor link.
这个类定义了一个接口来处理请求和选择性地实现了继任者链接。
Client:(客户)
This class initiates([i'niʃieits]发起) the request to a ConcreteHandler object on the chain.
这个类发起一个请求到责任链中一个具体的处理类对象
责任链主要重在责任分离处理,让各个节点各司其职。
责任链上的各个节点都有机会处理事务,但是也可能不会受理请求。
责任链比较长,调试时可能会比较麻烦。
责任链一般用于处理流程节点之类的实际业务场景中。
abstract class Handler { protected $_handler = null; public function setSuccessor($handler) { $this->_handler = $handler; } abstract function handleRequest($request); } class ConcreteHandlerZero extends Handler { public function handleRequest($request) { if ($request == 0) { echo "0"; } else { $this->_handler->handleRequest($request); } } } class ConcreteHandlerOdd extends Handler { public function handleRequest($request) { if ($request % 2) { echo $request . " is odd"; } else { $this->_handler->handleRequest($request); } } } class ConcreteHandlerEven extends Handler { public function handleRequest($request) { if (!($request % 2)) { echo $request . " is even"; } else { $this->_handler->handleRequest($request); } } } $objZeroHander = new ConcreteHandlerZero(); $objEvenHander = new ConcreteHandlerEven(); $objOddHander = new ConcreteHandlerOdd(); $objZeroHander->setSuccessor($objEvenHander); $objEvenHander->setSuccessor($objOddHander); foreach (array(2, 3, 4, 5, 0) as $row) { $objZeroHander->handleRequest($row); }
评论