Design mode-Mediator mode

Source: Internet
Author: User

definition: encapsulates a series of object interactions with a mediator object, which causes the objects to be loosely coupled and can independently change the interaction between them without displaying the interaction of the objects.

Type: behavior class mode

Class Diagram:

The structure of the mediator pattern

The mediator pattern, also known as the mediator pattern, is divided into 3 parts from the class diagram:

    • Abstract Mediator: Defines the interface of the colleague class object to the mediator object for communication between the individual colleague classes. Typically includes one or several abstract event methods, and is implemented by subclasses.
    • The Mediator implementation class: inherits from the abstract mediator and implements the event method defined in the abstract mediator. Receives a message from a colleague class and then affects other concurrent classes through the message.
    • Colleague class: If an object affects other objects and is also affected by other objects, these two objects are called colleague classes. In the class diagram, the colleague class has only one, this is actually the omission of reality, in the actual application, the colleague class generally consists of many, they influence each other and depend on each other. The more co-workers, the more complex the relationship. Also, a colleague class can be represented as a set of implementations that inherit the same abstract class. In the mediator mode, the peer class must pass through the mediator to deliver the message.

Why to use the mediator mode

In general, the relationship between colleague classes is more complex, and when multiple colleague classes are interrelated, their relationship is presented as a complex network structure, an overly-coupled architecture that is not conducive to the reuse of classes and is not stable. For example, there are six colleague class objects, and if object 1 changes, then 4 objects will be affected. If object 2 changes, then 5 objects will be affected. In other words, the design of the direct association between colleague classes is not good.

If you introduce the mediator pattern, then the relationship between the colleague classes becomes a star structure, and you can see that the change of any one class only affects the class itself and the mediator, thus reducing the coupling of the system. A good design must not encapsulate all of the object relational processing logic in this class, but instead use a specialized class to manage behaviors that are not theirs.

We use an example to illustrate what a colleague class is: There are two classes A and B, each with a number in the class, and to ensure that the number in class B is always 100 times times the number in Class A. That is, when you modify the number of Class A, multiply this number by 100 and assign it to Class B, while modifying Class B assigns the number divided by 100 to Class A. Class A b affects each other and is called a colleague class. The code is as follows:

Abstract class Abstractcolleague {protected int number;      public int GetNumber () {return number;      } public void Setnumber (int number) {this.number = number;  }//abstract method, modifying a number while modifying the associated object public abstract void Setnumber (int numbers, Abstractcolleague coll);          } class Colleaguea extends abstractcolleague{public void setnumber (int number, Abstractcolleague coll) {          This.number = number;      Coll.setnumber (number*100);           }} class Colleagueb extends abstractcolleague{public void setnumber (int number, Abstractcolleague coll) {          This.number = number;      Coll.setnumber (number/100); }} public class Client {public static void main (string[] args) {Abstractcolleague CollA = new Collea          Guea ();                    Abstractcolleague collb = new Colleagueb ();          System.out.println ("========== set a influence b==========");          Colla.setnumber (1288, COLLB); System.out.pRINTLN ("Number Value of CollA:" +colla.getnumber ());            SYSTEM.OUT.PRINTLN ("Number Value of COLLB:" +collb.getnumber ());          System.out.println ("========== set B affects a==========");          Collb.setnumber (87635, CollA);          SYSTEM.OUT.PRINTLN ("Number Value of COLLB:" +collb.getnumber ());      SYSTEM.OUT.PRINTLN ("Number Value of CollA:" +colla.getnumber ());  }  }

  In the code above, Class A B has a relationship with a direct association, and if we want to use the mediator pattern, the Class A Class B can not be directly related to each other, they must be through a mediator to achieve the purpose of the association.

Abstract class Abstractcolleague {protected int number;      public int GetNumber () {return number;      } public void Setnumber (int number) {this.number = number;  }//Note that the parameter here is no longer a colleague class, but a mediator public abstract void Setnumber (int number, abstractmediator am);          } class Colleaguea extends abstractcolleague{public void setnumber (int number, abstractmediator am) {          This.number = number; Am.      AAFFECTB (); }} class Colleagueb extends abstractcolleague{@Override public void setnumber (int number, Abstractmediat          Or am) {this.number = number; Am.      Baffecta ();      }} abstract class Abstractmediator {protected Abstractcolleague A;            protected Abstractcolleague B;          Public Abstractmediator (Abstractcolleague A, Abstractcolleague b) {a = A;      b = b;            } public abstract void Aaffectb ();    public abstract void baffecta (); } class MedIator extends Abstractmediator {public Mediator (Abstractcolleague A, Abstractcolleague b) {super (A, b);          }//deal with the effect of a on B public void Aaffectb () {int number = A.getnumber ();      B.setnumber (number*100);          }//deal with the effect of B on a public void baffecta () {int number = B.getnumber ();      A.setnumber (number/100); }} public class Client {public static void main (string[] args) {Abstractcolleague CollA = new Colleagu          EA ();                    Abstractcolleague collb = new Colleagueb ();                    Abstractmediator am = new Mediator (CollA, COLLB);          System.out.println ("========== by setting a influence b==========");          Colla.setnumber (AM);          SYSTEM.OUT.PRINTLN (the number value of the CollA is: "+colla.getnumber ());            System.out.println ("The number of the COLLB is 10 times times the value of a:" +collb.getnumber ());          System.out.println ("========== by setting B influence a==========");          Collb.setnumber (AM); System.out.println ("The number value of the COLLB is:" +collb.getnumber ());                System.out.println ("CollA is 0.1 times times the number of B:" +colla.getnumber ());   }  }

Although the code is relatively long, but it is relatively easy to understand, in fact, the original processing object relationship code to a mediation class, through this intermediary class to deal with the relationship between objects.

Advantages of the broker model

    • Proper use of the mediator pattern avoids over-coupling between colleague classes, making it possible to use the peer classes relatively independently.
    • Using the mediator pattern, you can transform a one-to-many association between objects into one-to-one associations, making relationships between objects easy to understand and maintain.
    • Using the mediator pattern, you can abstract the behavior and collaboration of objects, and be able to manipulate the interaction between objects more flexibly.

Applicable scenarios

In object-oriented programming, a class is bound to have dependencies on other classes, and completely independent classes are meaningless. It is also quite common for a class to rely on multiple classes at the same time, since there is a case that a one-to-many dependency has its rationality, and proper use of the mediator pattern can make the original messy object relationship clear, but if abused, it can have a reverse effect. In general, the use of the mediator pattern is only considered if the relationship between the peer class is a network structure. The mesh structure can be transformed into a star-like structure, making the relationship between colleague classes clearer.

The intermediary mode is a kind of more commonly used pattern, and it is also a more easily abused mode. For most cases, the relationship between colleague classes is not complex to a cluttered network structure, so in most cases it is possible to encapsulate the dependencies between objects within a colleague class, and there is no need to introduce a mediator pattern. Abusing the broker model will only make things more complicated.

C # example

Class Program {static void Main (string[] args) {//1. Create broker--motherboard object Concretemediator            Mediator = new Concretemediator ();            2. Create a colleague class Cddriver cd = new Cddriver (mediator);            CPU CPU = new CPU (mediator);            Videocard videocard = new Videocard (mediator);            Soundcard soundcard = new Soundcard (mediator); 3. Let the intermediary know all the colleagues mediator.            Setcddriver (CD); Mediator.            SetCPU (CPU); Mediator.            Setvideocard (Videocard); Mediator.            Setsoundcard (soundcard); 4. Start watching a movie CD.            READCD ();        Console.read ();    }} #region colleague abstract class///<summary>//Colleague abstract class///</summary> public abstract class colleague        {//holds a reference to the intermediary object, because each colleague class should know the intermediary object private mediator mediator;        constructor, incoming mediator object public colleague (mediator mediator) {this.mediator = mediator; }//Gets the current colleague class's mediator object public Mediator Getmediator () {return this.mediator; }} #endregion #region colleague specific class///<summary>//Optical drive class///</summary> public class Cddriver : colleague {public cddriver (Mediator mediator): base (mediator) {}///&LT;SU        Mmary>///CD/DVD///</summary> private string data = null; <summary>///Get data read from optical drive///</summary>//<returns></returns> P Ublic string GetData () {return this.        Data; The public void READCD () {///comma is before the video data, and after the comma is the sound data this.            data = "This is the video data, this is the sound data"; Notifies the motherboard that its own state has been reversed to change this. Getmediator ().        Change (this); }}///<summary>//CPU class///</summary> public class Cpu:colleague {public CPU (M Ediator mediator): base (mediator) {}///<sUmmary>///decomposition of video data///</summary> private string videiodata = null;        <summary>///decomposition of video data///</summary> private string sounddata = null; <summary>///Get decomposed video data///</summary>//<returns></returns> P        Ublic string Getvideiodata () {return this.videiodata;         }///<summary>///Get exploded sound data///</summary>//<returns></returns>        public string Getsounddata () {return this.sounddata;        }///<summary>//processing data///</summary> public void Executedata (string data) {string[] ss = data.            Split (', ');            This.videiodata = Ss[0];            This.sounddata = ss[1]; Notifies the motherboard that the CPU work has completed this. Getmediator ().        Change (this); }}///<summary>///Graphics class//</summary> public class Videocard:colleague {public videocard (Mediator mediator): base (M Ediator) {}///<summary>///display video data source///</summary> public void Sh        Owdata (String data) {Console.WriteLine ("You are looking at:" + data); }}///<summary>///audio///</summary> public class Soundcard:colleague {public        Soundcard (Mediator Mediator): base (mediator) {}//<summary>///display sound data source         </summary> public void ShowData (string data) {Console.WriteLine ("You are listening:" + data); }} #endregion #region Broker abstract class///<summary>//Broker abstract class///</summary> public ABS    Tract class Mediator {public abstract void change (colleague colleague); #endregion #region Intermediaries specific classes///<summary>//Intermediaries specific classes///</summary> PUblic class Concretemediator:mediator {private Cddriver cddriver;        Private CPU CPU;        Private Videocard video;        Private soundcard sound;        public void Setcddriver (Cddriver cddriver) {this.cddriver = Cddriver;        } public void SetCPU (CPU CPU) {THIS.CPU = CPU;        } public void Setvideocard (Videocard video) {this.video = video;        } public void Setsoundcard (Soundcard sound) {this.sound = sound;                public override void Change (colleague colleague) {if (colleague = = Cddriver) {            Opencdandreaddata ((Cddriver) colleague);            } else if (colleague = = CPU) {OPENCPU (CPU) colleague); }}///<summary>//Open CD and read data///</summary>//<param Name= "cs" > </param> private void OpencdandReadData (Cddriver CS) {//Gets the data read by the optical drive as a string: Cddriver.getdata ();        Pass this data to the CPU for processing this.cpu.ExecuteData (data); }///<summary>//CPU processing//</summary>//<param name= "CPU" ></param&gt        ; private void Opencpu (CPU CPU) {//Get data string videodata = CPU.            Getvideiodata (); String sounddata = CPU.            Getsounddata ();            Display Data this.video.ShowData (videodata);        This.sound.ShowData (Sounddata); }} #endregion

Understanding patterns (through the example above)

1. Function of the mediator mode

The function of a mediator is to encapsulate the interaction between objects. If an object's actions cause other related objects to change, and this object does not want to handle these relationships yourself, then you can go to the mediator and let it handle these troublesome relationships.

2. Do I need a mediator interface?

The question, first of all, you have to figure out what the interface is for? Interface is used to "encapsulate the isolation", the mediator interface is used to encapsulate the Mediator object, so that the client object of the intermediary object and the specific intermediary implementation of the object separated.

If there is only one intermediary object that is not intended to be extended, then the mediator interface can be undefined.

3. Colleague Relations

In the standard mediator pattern, those objects that use the Mediator object to interact with are called colleague classes, which require that these classes inherit from the same class, that is, they are sibling objects.

4. Relationship between co-workers and intermediaries

In a pattern, when a colleague object changes, you need to proactively notify the mediator and let the mediator handle the interaction with other colleague objects.

This causes the colleague object to have a relationship with the mediation object, the colleague object needs to know the mediation object for notification, and the mediation object needs to know the colleague object and interact with it. All of their relationships are interdependent.

5. How to achieve communication between co-workers and intermediaries

One way is to define a special notification interface in the mediator interface as a common method for each colleague to invoke this method.

The other is to use the observer pattern, the implementation of mediator to become an observer, each colleague object is implemented as subject. When these colleague objects change, the mediator is notified.

6. Generalized intermediaries

In real-world development, it is often easier to simplify the broker pattern, to make it easier to develop, such as the following simplification.

L usually get rid of the parent class of the colleague object, so that any object, only need to have interaction, can become a colleague

L usually do not define the mediator interface, the specific intermediary object implementation into a single case

L The colleague object no longer holds the intermediary, but takes the intermediary object and invokes it directly when needed, and the intermediary no longer holds the colleague object, but creates, acquires, or passes in the required colleague object from the data in the concrete processing method.

After such simplification, deformation is referred to as the generalized mediator.

7. When to choose the intermediary mode

If the communication between a group of objects is more complex, resulting in mutual dependence, structural confusion, you can use the intermediary mode

If an object references many objects and interacts with those objects, it is difficult to take the object

8. Model Nature

The essence of the mediator pattern is "encapsulation interaction"

The purpose of the mediator pattern is to encapsulate the interaction of multiple objects, which are implemented in the intermediary object.

As long as the interaction of the encapsulated object is implemented, the mediator pattern can be used, rather than the schema structure.

9. Related modes

Mediator mode and appearance mode

The appearance mode is used to encapsulate multiple modules inside a subsystem to provide an easy-to-use interface outside the subsystem.

The mediator pattern is the encapsulation that provides the interaction between multiple equal colleague objects, which is generally used in the internal implementation.

Mediator mode and Observer pattern

These two patterns can be used in combination.

The mediator pattern can be used in combination with the observer pattern to inform the mediation object when a colleague object changes, and let the mediation object interact with other related objects.

Design mode-Mediator mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.