设为首页 加入收藏

TOP

Chain of Responsibility - 职责链模式
2015-07-24 05:34:01 来源: 作者: 【 】 浏览:6
Tags:Chain Responsibility 职责 模式
定义 使多个对象都有机会处理请求,从而避免请求的发送者和接受者之间的耦合度。
案例 比如现在有一个图形界面,它包括一个应用Application类,一个主窗口Window,一个按钮Button,Window和Button都是继承自Widget类,现在在Button上按滑动鼠标滚轮,Button类不一定要处理,可能是Window类处理,也可能是是Application类处理,每一个类只处理自己关心的,从一个链式结构,以此查看是否要处理: \
\
每一个对象都有处理事件的权利,当不处理的时候就会交给父对象处理:
  
  1. Class EventHandler {
  2. public:
  3. EventHandler(EventHandler* eh) : m_handler(eh) { }
  4. virtual void handle(Event* e) { if (m_handler) m_handler->handle(e); }
  5. private:
  6. EventHandler* m_handler;
  7. }
  8. class Application : EventHandler {
  9. public:
  10. Applicatoin();
  11. void exec() { ... }
  12. }
  13. class Widget : EventHandler {
  14. public:
  15. Widget(Widget* parent) : EventHandler(parent) { }
  16. void draw() { ... }
  17. }
  18. class Window : public Widget {
  19. public:
  20. virtual void handle(Event* e) {
  21. if(e->type() == WheelEvent)
  22. ...;
  23. else
  24. Widget::Handle(e);
  25. }
  26. }
  27. class Button : public Widget{
  28. public:
  29. virutal void handle(Event* e) {
  30. if(e->type == MousePressEvent)
  31. ...
  32. else
  33. Widget::handle(e);
  34. }
  35. }
  36. int main()
  37. {
  38. Application app;
  39. Widget widget;
  40. Button button(widget);
  41. return app.exe();
  42. }
Button只处理鼠标按钮的时间,像滚轮的事件就会继续发送出去,恰好的父控件的时候可以处理,父控件就会处理掉。
适用性 有多个对象可以处理一个请求,具体哪个对象处理运行时刻确定。在不想指明接受者的情况下。 优缺点 降低了 系统的耦合度,请求处理和处理对象之间没有明确关系。增强了给对象指派指责的灵活性。不保证被一个对象能处理请求。
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Proxy - 代理模式 下一篇hdu 4644 BWT (kmp)

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: