案例 比如现在有一个图形界面,它包括一个应用Application类,一个主窗口Window,一个按钮Button,Window和Button都是继承自Widget类,现在在Button上按滑动鼠标滚轮,Button类不一定要处理,可能是Window类处理,也可能是是Application类处理,每一个类只处理自己关心的,从一个链式结构,以此查看是否要处理:
Button只处理鼠标按钮的时间,像滚轮的事件就会继续发送出去,恰好的父控件的时候可以处理,父控件就会处理掉。
Class EventHandler {public:EventHandler(EventHandler* eh) : m_handler(eh) { }virtual void handle(Event* e) { if (m_handler) m_handler->handle(e); }private:EventHandler* m_handler;}class Application : EventHandler {public:Applicatoin();void exec() { ... }}class Widget : EventHandler {public:Widget(Widget* parent) : EventHandler(parent) { }void draw() { ... }}class Window : public Widget {public:virtual void handle(Event* e) {if(e->type() ==WheelEvent)...;elseWidget::Handle(e);}}class Button : public Widget{public:virutal void handle(Event* e) {if(e->type == MousePressEvent)...elseWidget::handle(e);}}int main(){Application app;Widget widget;Button button(widget);return app.exe();}
适用性 有多个对象可以处理一个请求,具体哪个对象处理运行时刻确定。在不想指明接受者的情况下。 优缺点 降低了 系统的耦合度,请求处理和处理对象之间没有明确关系。增强了给对象指派指责的灵活性。不保证被一个对象能处理请求。