设计模式:chain of responsibility模式
目的:弱化发出请求的对象和处理请求对象的之间的关系
理解:每个处理请求的对象仅仅只关注自己能处理的请求,不关系其他请求
优点:
- 无需一个管理类来匹配所有的请求,更灵活
- 责任链可以动态的调整
- Andorid中事件处理框架就使用了责任链模式
继承关系图:
例子:
class Trouble { int num; public: Trouble(int num) { this->num = num; } int getNum() { return num; } };
class Handler { string name; Handler* next; public: Handler(string name) { this->name = name; next = NULL; } Handler* setNext(Handler* next) { this->next = next; return next; } void handler(Trouble* t) { if(resolve(t)) { cout << "Trouble num = " << t->getNum() << " is solve by " << name << endl; } else if(next != NULL) { next->handler(t); } else { cout << "Trouble num = " << t->getNum() << " can't solve" << endl; } } virtual bool resolve(Trouble* t) { return false; } }; class LittleHandler: public Handler { public: LittleHandler(string name) : Handler(name) { } virtual bool resolve(Trouble* t) { bool ret = false; if(t->getNum() < 10) { ret = true; } return ret; } }; class BiggerHandler: public Handler { public: BiggerHandler(string name) : Handler(name) { } virtual bool resolve(Trouble* t) { bool ret = false; if(t->getNum() > 10) { ret = true; } return ret; } };
int main() { Handler* h = new Handler("handler"); LittleHandler* lh = new LittleHandler("littleHandler"); BiggerHandler* bh = new BiggerHandler("biggerHandler"); h->setNext(lh)->setNext(bh); Trouble* t1 = new Trouble(5); h->handler(t1); Trouble* t2 = new Trouble(15); h->handler(t2); return 0; }