码迷,mamicode.com
首页 > 其他好文 > 详细

Chain of Responsibility - 职责链模式

时间:2014-07-12 23:29:27      阅读:264      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   strong   os   

定义
使多个对象都有机会处理请求,从而避免请求的发送者和接受者之间的耦合度。

案例
比如现在有一个图形界面,它包括一个应用Application类,一个主窗口Window,一个按钮Button,Window和Button都是继承自Widget类,现在在Button上按滑动鼠标滚轮,Button类不一定要处理,可能是Window类处理,也可能是是Application类处理,每一个类只处理自己关心的,从一个链式结构,以此查看是否要处理:
bubuko.com,布布扣
bubuko.com,布布扣
每一个对象都有处理事件的权利,当不处理的时候就会交给父对象处理:
  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只处理鼠标按钮的时间,像滚轮的事件就会继续发送出去,恰好的父控件的时候可以处理,父控件就会处理掉。

适用性
  • 有多个对象可以处理一个请求,具体哪个对象处理运行时刻确定。
  • 在不想指明接受者的情况下。
优缺点
  1. 降低了系统的耦合度,请求处理和处理对象之间没有明确关系。
  2. 增强了给对象指派指责的灵活性。
  3. 不保证被一个对象能处理请求。

Chain of Responsibility - 职责链模式,布布扣,bubuko.com

Chain of Responsibility - 职责链模式

标签:style   blog   http   color   strong   os   

原文地址:http://blog.csdn.net/harrising/article/details/37671707

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!