Design Pattern --- Mediator
class AList; class AButton; class AEdit; class Director { // data. AList *m_list; AButton *m_button; AEdit *m_edit; public: // Interface. void Init(AList *l, AButton *b, AEdit *e) { m_list = l, m_button = b, m_edit = e; } void foo_bazBar(); void bar_baz(); }; class AList { // data. Director *m_director; public: AList(Director *d) : m_director(d) {} public: // Interface void foo() { cout <<"AList::foo()." <<endl; m_director->foo_bazBar(); // 通过 Director 通知其它的控件. } }; class AButton { // data. Director *m_director; public: AButton(Director *d) : m_director(d) {} public: // Interface void bar() { cout <<"AButton::bar()." <<endl; m_director->bar_baz(); // 通过 Director 通知其它的控件. } }; class AEdit { // data. Director *m_director; public: AEdit(Director *d) : m_director(d) {} public: // Interface void baz() { cout <<"AEdit::baz()." <<endl; } }; void Director::foo_bazBar() { m_edit->baz(); m_button->bar(); } void Director::bar_baz() { m_edit->baz(); } int main() { Director *d = new Director; AList *l = new AList(d); AButton *b = new AButton(d); AEdit *e = new AEdit(d); d->Init(l, b, e); l->foo(); // TODO: Release memory. return 0; }
此模式与 Observer 模式非常相似, 都是找一个转发中心 (此例中 Directory), 作为所有不相关控件 (如 AList 和 AButton) 的控制者. 这些不相关的控件, 向 Director 申请一些操作, Director 便会找到相应的对象并执行操作.