Communication between two classes, not through direct communication, but in the middle plus a layer similar to the intermediary class, intermediary mode, on the analogy of renting the intermediary that will
//Mediator.cpp:Defines the entry point for the console application.//#include"stdafx.h"#include<string>#include<VECTOR>#include<iostream>using namespacestd;classcolleague{//abstract Colleague Class Public: Colleague (stringname): M_name (name) {}Virtual voidSendmsg (stringmsg) =0; Virtual voidNotifyrecvivemsg (stringmsg) =0; stringgetname () {returnM_name; } Virtual~colleague () {}Private: stringm_name;};classmediator{//Abstract Mediator Class Public: Virtual voidSendstringMsg,colleague * des) =0; Virtual voidAddGroup (colleague * p) =0; Virtual~Mediator () {}};classConcreatemediator: Publicmediator{//Specific Intermediaries Public: voidSendstringMsg,colleague *Res) {cout<<res->getname () <<"Send msg:"<<msg<<Endl; if(Res! = covec[0]) covec[0]->notifyrecvivemsg (msg); Elsecovec[1]->notifyrecvivemsg (msg); } voidAddGroup (Colleague *p) {Covec.push_back (P); }Private: Vector<colleague * >Covec;};classConcreatecolleague: Publiccolleague{//specific colleagues Public: Concreatecolleague (stringName,mediator *Media): colleague (name) {Pmedia=Media; } voidSendmsg (stringmsg) {Pmedia->send (MSG, This);//sent by the mediator, then the mediator reminds the recipient to receive } voidNotifyrecvivemsg (stringmsg) {cout<< This->getname () <<"recv msg:"<<msg<<Endl; }Private: Mediator*Pmedia;};intMainintargcChar*argv[]) {Concreatemediator* Pmedia =NewConcreatemediator (); Colleague* Worker1 =NewConcreatecolleague ("Xiaowang", Pmedia); Colleague* Worker2 =NewConcreatecolleague ("Xiaohong", Pmedia); Pmedia-AddGroup (Worker1); Pmedia-AddGroup (WORKER2); Worker1->sendmsg ("Hello"); Worker2->sendmsg ("Nihaoa"); DeleteWorker1; DeleteWorker2; DeletePmedia; return 0;}
Mediation Mode Mediator