设计模式之职责链模式
【定义】职责链模式(Chain of Responsibility),使多个对象都有机会处理请求,从而避免请求的发送者和接受者之间的偶合关系。将这个对象练成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。
【UML】
【代码】
#include <iostream> using namespace std; class Handle { protected: Handle* next_handle; public: void set_next_handle(Handle* handle) { next_handle = handle; } virtual void handle_request(int value) = 0; }; class ConcreteHandleA:public Handle { public: void handle_request(int value) { if(value < 0) { cout<<"ConcretHandleA value:"<<value<<endl; } else if(NULL != next_handle) { next_handle->handle_request(value); } } }; class ConcreteHandleB:public Handle { public: void handle_request(int value) { if(value == 0) { cout<<"ConcretHandleB value:"<<value<<endl; } else if(NULL != next_handle) { next_handle->handle_request(value); } } }; class ConcreteHandleC:public Handle { public: void handle_request(int value) { if(value > 0) { cout<<"ConcretHandleC value:"<<value<<endl; } else if(NULL != next_handle) { next_handle->handle_request(value); } } }; int main() { Handle* a = new ConcreteHandleA; Handle* b = new ConcreteHandleB; Handle* c = new ConcreteHandleC; a->set_next_handle(b); b->set_next_handle(c); a->handle_request(-1); a->handle_request(0); a->handle_request(4); delete a; delete b; delete c; return 0; }
【运行结果】
不积跬步无以至千里,不积小流无以成江河。