标签:
1.意图
使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。
2.动机
给多个对象处理一个请求的机会,从而解耦发送者和接收者。
3.适用性
4.结构
5.代码实例
//Handler.h #include <memory> class AbstractHandler { public: virtual void HandleRequest() = 0; virtual void SetHandler(std::shared_ptr<AbstractHandler> pHandler); protected: std::shared_ptr<AbstractHandler> m_pHandler; }; class BaseHandler : public AbstractHandler { public: virtual void HandleRequest(); }; class ConcreteHandler1 : public BaseHandler { public: void HandleRequest(); }; class ConcreteHandler2 : public BaseHandler { public: void HandleRequest(); };
//Handler.cpp #include <iostream> #include "Handler.h" void AbstractHandler ::SetHandler(std::shared_ptr<AbstractHandler> pHandler) { m_pHandler = pHandler; }; void BaseHandler ::HandleRequest() { std::cout << "Base Handler Handled" << std::endl; }; void ConcreteHandler1 ::HandleRequest() { std::cout << "ConcreteHandler1 Handled" << std::endl; m_pHandler->HandleRequest(); }; void ConcreteHandler2 ::HandleRequest() { std::cout << "ConcreteHandler2 Handled" << std::endl; m_pHandler->HandleRequest(); };
//client #include "Handler.h" int main() { std::shared_ptr <AbstractHandler> pConcreteHandler1(new ConcreteHandler1); std::shared_ptr <AbstractHandler> pConcreteHandler2(new ConcreteHandler2); std::shared_ptr <AbstractHandler> pBaseHandler(new BaseHandler); pConcreteHandler1->SetHandler(pConcreteHandler2); pConcreteHandler2->SetHandler(pBaseHandler); pConcreteHandler1->HandleRequest(); while(1); }
6.测试结果
以上结果为每个handler执行后均调用上一级的handler执行。
7.效果
Chain Of Responsibility(职责连)-对象行为型模式
标签:
原文地址:http://www.cnblogs.com/mgp200866130/p/5616558.html