Design Pattern --- Chain of Responsibility
class Window { protected: Window *m_successor; bool m_msg; public: Window(Window *successor, bool msg) : m_successor(successor), m_msg(msg) {} public: // Interface. virtual void Msg() { if (m_msg) { showMsg(); } else { if (m_successor != nullptr) { m_successor->Msg(); } } } private: // logic. virtual void showMsg() { cout <<"Window." <<endl; } }; class Dialog : public Window { public: Dialog(Window *successor, bool msg) : Window(successor, msg) {} private: // logic. virtual void showMsg() override { cout <<"Dialog." <<endl; } }; class Button : public Window { public: Button(Window *successor, bool msg) : Window(successor, msg) {} private: // logic. virtual void showMsg() override { cout <<"Button." <<endl; } }; int main(int argc, char *argv[]) { Window app(nullptr, true); Dialog dlg(&app, true); // false. Button btn(&dlg, false); btn.Msg(); // 链式向上查找, 直到有一个能处理请求为止。非常适合消息处理机制。 return 0; }