Overview:
An intermediary object is used to encapsulate a series of object interactions. The intermediary makes the objects do not need to be explicitly referenced to each other, so that the coupling is loose and the interaction between them can be changed independently.
Applicability;
1. A group of objects communicate in a well-defined but complex manner. The resulting dependency structure is confusing and hard to understand. 2. An object references many other objects and communicates directly with these objects, making it difficult to reuse the object. 3. You do not want to generate too many child classes if you want to customize a behavior distributed across multiple classes.
Participants:
1. The mediator intermediary defines an interface to communicate with colleagues objects. 2. concretemediator a specific intermediary can coordinate various colleagues' objects to implement collaborative behavior. Understand and maintain its colleagues. 3. colleagueclass every colleague class knows its intermediary object. When a colleague object needs to communicate with other colleagues, it communicates with its intermediary
Class diagram:
Example:
Mediator public abstract class Mediator { public abstract void notice(String content);}
Concretemediator Public class concretemediator extends mediator {private colleaguea CA; private colleagueb CB; Public concretemediator () {CA = new colleaguea (); Cb = new colleagueb ();} public void notice (string content) {If (content. equals ("boss") {// The Boss is here to notify the employee a ca. action ();} If (content. equals ("client") {// The customer has arrived, notifying the front-end B CB. action ();}}}
Colleagueclass Public class colleaguea extends colleague {public void action () {system. Out. println ("ordinary employee working hard ");}}
Public class colleagueb extends colleague {public void action () {system. Out. println ("front-end attention! ");}}
Test Public class test {public static void main (string [] ARGs) {mediator med = new concretemediator (); // The boss came to Med. notice ("boss"); // The customer came to Med. notice ("client ");}}
Result Ordinary employees have worked hard at the front-end!
Reproduced from Java design mode (crazy Java Alliance)