Mediator Mode (mediator): Uses a Mediation object to encapsulate a series of object interactions. Intermediaries are objects that do not need to explicitly reference each other, so that they are loosely coupled and can independently change their interactions.
The broker pattern is easy to apply in the system and is easily misused in the system. When the system appears many-to-many interaction complex object group is, do not rush to use the intermediary mode, but first to reflect on the design of your system is not reasonable.
Advantages: The appearance of the mediator reduces the coupling of each colleague, allowing the individual colleague classes and mediator to be independently changed and reused; Because of how objects work together, the mediations are abstracted as an independent concept and encapsulated in an object. The object of such attention is shifted from the behavior of the objects themselves to the interaction between them, that is, to stand in a more macroscopic view of the system.
The mediator pattern is typically applied to a set of objects in a well-defined but complex way to communicate, and to customize a behavior that is distributed across multiple classes without having to generate too many subclasses.
#ifndef mediator_h#define mediator_h#include<iostream> #include <string>using namespace Std;class Country ; class unitednations{public:virtual void Declare (String message, country *colleague) = 0;}; Class Country{protected:unitednations *mediator;public:country () {}country (unitednations *m): Mediator (m) {}virtual void Declare (string m) = 0;virtual void GetMessage (string st) = 0;}; Class USA:p ublic Country{public:usa (unitednations *m) {mediator = m;} void Declare (string m) {Mediator->declare (M, this);} void GetMessage (string m) {cout << "The United States obtains information about the other:" << m << Endl;}}; Class Iraq:p ublic Country{public:iraq (unitednations* m) {mediator = m;} void Declare (string m) {Mediator->declare (M, this);} void GetMessage (string m) {cout << "Iraq obtains information about the other:" << m << Endl;}}; Class Unitednationssecuritycouncil:p ublic unitednations{country * colleague1; Country * colleague2;public:void SetColleague1 (Country * C1) {colleague1 = C1;} void SetColleague2 (Country * C2) {colleague2 = C2; }void Declare (String message, country *colleague) {if (colleague = = colleague1) colleague2->getmessage (message); Elsecolleague1->getmessage (message);}}; #endif
#include "Mediator.h" int main () {Unitednationssecuritycouncil UNSC; USA USA (&UNSC); Iraq Iraq (&UNSC); UNSC. SetColleague1 (&USA); UNSC. SetColleague2 (&iraq), USA. Declare ("No nuclear weapons should be developed, or war will be waged!") "); Iraq. Declare ("We have no nuclear weapons, we are not afraid of aggression!" "); return 0;}
Design pattern C + + implementation 21: Broker mode