Chain of 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只处理鼠标按钮的时间,像滚轮的事件就会继续发送出去,恰好的父控件的时候可以处理,父控件就会处理掉。

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值