一、意图:
使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。
二、类图:
三、组成元素:
Handler:请求接口;
ConcreteHandler:具体处理请求的接口;
四、实现代码:
#include<iostream> using namespace std; class Handler { public: Handler(Handler* p = 0) : pHandler(p) { } virtual void setSuccessor( Handler* pH) { pHandler = pH; } virtual void handlerRequest(int request){ } protected: Handler* pHandler; }; class ConcreteHandler1 : public Handler { public: ConcreteHandler1(Handler* p ) : Handler( p ) { } void handlerRequest( int request ) { if (request >=0 && request<= 10) { cout<<"request= "<<request<<" handler"<<endl; } else { pHandler->handlerRequest(request); } } }; class ConcreteHandler2 : public Handler { public: ConcreteHandler2(Handler* p) : Handler( p ) { } void handlerRequest( int request ) { if (request >=10 && request<= 20) { cout<<"request= "<<request<<" handler"<<endl; } else { pHandler->handlerRequest(request); } } }; class ConcreteHandler3 : public Handler { public: ConcreteHandler3(Handler* p) : Handler( p ) { } void handlerRequest( int request ) { if (request >=20 && request<= 30) { cout<<"request= "<<request<<" handler"<<endl; } else { cout<<"本类一定要处理一切情况"<<endl; //pHandler->handlerRequest(request); } } }; void main() { Handler* p1 = new ConcreteHandler1(0); //p1->handlerRequest(3); 测试 Handler* p2 = new ConcreteHandler2(0); Handler* p3 = new ConcreteHandler3(0); p1->setSuccessor(p2); p2->setSuccessor(p3); int a[] = {7,9,16,13,18,21,35 }; for ( int i = 0 ; i<= 6 ; ++i ) { p1->handlerRequest(a[i]); } }