一、功能
使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。
二、优缺点
客户不知道它的请求将被哪个对象处理。
三、实现
有两种实现思路。一种是自己先处理,处理不成功了再交给其他人处理。另一种是先交给别人处理,处理不成功了再自己处理。示例代码如下节所示。四、示例代码
(1)示例一
namespace DesignPattern_ChainOfResponsibility { // class Handler class Handler { public: Handler(Handler *pSuccessor = NULL) : _successor(pSuccessor) {} virtual void HandleRequest() { (_successor) ? _successor->HandleRequest() : 0 ; } private: Handler *_successor ; } ; // class ConcreteHandler1 class ConcreteHandler1 : public Handler { public: ConcreteHandler1(Handler *pSuccessor = NULL) : Handler(pSuccessor) {} virtual void HandleRequest() { bool bHandled = true ; // do some operations (!bHandled) ? Handler::HandleRequest() : 0 ;//如果处理失败就交给下一个对象处理 } } ; // class ConcreteHandler2 class ConcreteHandler2 : public Handler { public: ConcreteHandler2(Handler *pSuccessor = NULL) : Handler(pSuccessor) {} virtual void HandleRequest() { bool bHandled = true ; // do some operations (!bHandled) ? Handler::HandleRequest() : 0 ;//如果处理失败就交给下一个对象处理 } } ; }
(2)示例二
namespace DesignPattern_ChainOfResponsibility { // class Handler class Handler { public: Handler(Handler *pSuccessor = NULL) : _successor(pSuccessor) {} virtual bool HandleRequest() //返回true表示处理成功,返回false表示处理失败 { return (_successor) ? _successor->HandleRequest() : false ; } private: Handler *_successor ; } ; // class ConcreteHandler1 class ConcreteHandler1 : public Handler { public: ConcreteHandler1(Handler *pSuccessor = NULL) : Handler(pSuccessor) {} virtual bool HandleRequest() { bool bHandled = true ; if (!Handler::HandleRequest()) //如果下一个对象处理失败就自己处理 { // do some operations // set bHandled to 'true' or 'false' according to if handle successfully } return bHandled ; } } ; // class ConcreteHandler2 class ConcreteHandler2 : public Handler { public: ConcreteHandler2(Handler *pSuccessor = NULL) : Handler(pSuccessor) {} virtual bool HandleRequest() { bool bHandled = true ; if (!Handler::HandleRequest()) //如果下一个对象处理失败就自己处理 { // do some operations // set bHandled to 'true' or 'false' according to if handle successfully } return bHandled ; } } ; }