【1】什么是中介者模式? 中介者模式: 【2】中介者模式代码示例: 代码示例:
#include<iostream> #include <string> using namespace std; class Mediator; class ConcreteColleague1; class ConcreteColleague2; class Colleague { protected: Mediator *mediator; public: Colleague(Mediator *mediator) { this->mediator = mediator; } }; class ConcreteColleague1 : public Colleague { public: ConcreteColleague1(Mediator *mediator) : Colleague(mediator) {} void send(string message); void notify(string message) { cout << "同事1得到消息: " << message << endl; } }; class ConcreteColleague2 : public Colleague { public: ConcreteColleague2(Mediator *mediator) : Colleague(mediator) {} void send(string message); void notify(string message) { cout << "同事2得到消息: " << message << endl; } }; class Mediator { public: virtual void send(string name, Colleague *colleague)=0; }; class ConcreteMediator : public Mediator { public: ConcreteColleague1 *colleague1; ConcreteColleague2 *colleague2; public: void send(string message, Colleague *colleague) { if (colleague == colleague1) { colleague2->notify(message); } else { colleague1->notify(message); } } }; void ConcreteColleague1::send(string message) { mediator->send(message, this); } void ConcreteColleague2::send(string message) { mediator->send(message, this); } int main() { ConcreteMediator *m = new ConcreteMediator(); ConcreteColleague1 *c1 = new ConcreteColleague1(m); ConcreteColleague2 *c2 = new ConcreteColleague2(m); m->colleague1 = c1; m->colleague2 = c2; c1->send("吃饭啦"); c2->send("去 "); return 0; } //Result: /* 同事2得到消息: 吃饭啦 同事1得到消息: 去 */
代码示例2:
#include<iostream> #include <string> using namespace std; class Country; class UniteNations { public: virtual void declare(string message, Country *colleague) = 0; }; class Country { protected: UniteNations *mediator; public: Country(UniteNations *mediator) { this->mediator = mediator; } }; class USA : public Country { public: USA(UniteNations *mediator) : Country(mediator) {} void declare(string message) { mediator->declare(message, this); } void getMessage(string message) { cout << "美国获得对方信息: " << message << endl; } }; class Iraq : public Country { public: Iraq(UniteNations *mediator):Country(mediator) {} void declare(string message) { mediator->declare(message, this); } void getMessage(string message) { cout << "伊拉克获得对方信息: " << message << endl; } }; class UnitedNationsSecurityCouncil:public UniteNations { public: USA *usa; Iraq *iraq; void declare(string message, Country *colleague) { if (colleague == usa) { iraq->getMessage(message); } else { usa->getMessage(message); } } }; int main() { UnitedNationsSecurityCouncil *unsc = new UnitedNationsSecurityCouncil(); USA *c1 = new USA(unsc); Iraq *c2 = new Iraq(unsc); unsc->usa = c1; unsc->iraq = c2; c1->declare("不准开发核武器,否则打你!"); c2->declare("他妈的美国去死!"); return 0; } //Result: /* 伊拉克获得对方信息: 不准开发核武器,否则打你! 美国获得对方信息: 他妈的美国去死! */
转载自:http://www.cnblogs.com/Braveliu/p/3956897.html
时间: 2024-10-23 07:36:52