重温设计模式--中介者模式

时间:2024-12-25 07:02:42
#include<iostream> #include<string> using namespace std; class Country; //抽象类 联合国 class UN { public: virtual void delcare(string message , Country *m_country){} virtual void initcountry(Country*s1,Country*s2){}; }; //国家 class Country { protected: UN *m_un; public: Country(UN* name):m_un(name){} virtual void delcare(string m_message){} }; //美国 class USA:public Country { public: USA(UN* name):Country(name){} void delcare(string message) { cout<<"美国: "<<message<<endl; } }; //伊拉克 class Iraq:public Country { public: Iraq(UN* name):Country(name){} void delcare(string message) { cout<<"伊拉克:"<<message<<endl; } }; //安理会 class Security:public UN { private: Country *m_usa; Country *m_iraq; public: void initcountry(Country*s1 , Country*s2) { m_usa = s1; m_iraq = s2; } void delcare(string message , Country *m_country) { if(m_country==m_usa) { m_usa->delcare(message); } else { m_iraq->delcare(message); } } }; int main() { UN *m_sec = new Security();//创建安理会 Country*country_usa = new USA(m_sec);//创建美国 Country*country_iraq = new Iraq(m_sec);//创建伊拉克,美国和伊拉克有共同的中介者:安理会,m_sec m_sec->initcountry(country_usa,country_iraq); m_sec->delcare("我要干死你" , country_usa); m_sec->delcare("来呀,cnm,互相伤害呀" , country_iraq); cout<<endl<<endl; return 0; }