中介者模式
简介
通过引入一个中介者对象来封装和协调多个对象之间的交互,从而降低对象间的耦合度。
人话
:就是两个类或者系统之间, 不要直接互相调用, 而是要中间的类来专门进行交互。
举个例子
比如两个国家之间(关系差, 没有大使馆), 需要联合国作为中介进行对话.
class Country;class UnitedNations
{
public:vector<Country*> _countries;void add_contry(Country* c);void send(string s);
};class Country
{
private:UnitedNations* un;
public:Country(UnitedNations* u) : un(u) {};UnitedNations* get_un() { return un; };virtual void speek(string s) = 0;virtual void listen(string s) = 0;
};void UnitedNations::add_contry(Country* c)
{_countries.push_back(c);
}void UnitedNations::send(string s)
{for (Country* c : _countries)c->listen(s);
}class China : public Country
{
public:China(UnitedNations* un) : Country(un) {};void speek(string s) override{cout << "China said : " << s << endl;get_un()->send(s);}void listen(string s)override{cout << "----China get : " << s << endl;}
};class America : public Country
{
public:America(UnitedNations* un) : Country(un) {};void speek(string s) override{cout << "America said : " << s << endl;get_un()->send(s);}void listen(string s)override{cout << "----America get : " << s << endl;}
};class Russia : public Country
{
public:Russia(UnitedNations* un) : Country(un) {};void speek(string s) override{cout << "Russia said : " << s << endl;get_un()->send(s);}void listen(string s)override{cout << "----Russia get : " << s << endl;}
};int main()
{UnitedNations* un = new UnitedNations();China* c = new China(un);America* a = new America(un);Russia* r = new Russia(un);un->add_contry(c);un->add_contry(a);un->add_contry(r);r->speek("美国, 你爹来了");a->speek("呵呵, 笑死");c->speek("大家文明讲话");return 0;
}
执行结果