Design Patterns nine: intermediary model (Mediator)

In real life, often it appears there is a complex interaction between many objects, such interactions are often "network", which requires that each object must know that it needs to interact with objects. For example, each person must remember him (her) friends of all telephone; moreover, friends in someone's phone if modified, he (she) must inform all the other friends modifications, this is called "affect the situation as a whole" ,very complicated.

If such a "network" to "star structure", it will greatly reduce the "coupling" between them, then just find a "mediator" it. As previously said, "Everyone must remember all my friends call" problem, as long as the establishment of a "address book" a friend of each can access the Internet solved. There are many such examples, for example, you just want to rent SHENLIBAO mouth work, you can find "real estate agent"; or, that he had just a strange city to find a job, you can find the "talent exchange center" to help.

In the software development process, there are many such examples, e.g., in the MVC framework, the controller (C) is a model (M) and the View (V) of the intermediary; and "mediation we used QQ chat program who "is the QQ server. All this can be used "intermediary model" is implemented, it will greatly reduce the coupling between objects, increase the flexibility of the system.

The definition and characteristics of the model

Defined Mediator (Mediator) mode: a mediation object to encapsulate the definition of the interaction between a series of objects, the coupling between the loose objects original, and may be varied independently of the interaction between them. Intermediary model called the mediation model, which is a typical application of the Law of Demeter.

Mediator object behavioral pattern is a pattern, the main advantages are as follows.

  1. Reducing the coupling between objects, objects that are easily multiplexed independently.
  2. The many associations between objects into one association to improve the flexibility of the system, making the system easy to maintain and extend.


Its main drawback is: when a co-worker class too, will be a great mediator role, it becomes complicated and large that the system difficult to maintain.

Architecture and Implementation Model

The key intermediary model to achieve is to find the "mediator", the following structure and implementation of its analysis.

1. Structure Model

Intermediary model consists of the following major role.

  1. Abstract Mediator (Mediator) role: it is the mediator interface provides an abstract object registration and forwarding method colleagues colleagues object information.
  2. Specific mediator (ConcreteMediator) role: mediator implement an interface, define a colleague List to manage objects, coordinate the interactions between the various roles colleagues, so it depends on the role of co-workers.
  3. Colleagues abstract class (Colleague) roles: the definition of colleagues like interface, saving an intermediary object that provides an abstract method colleagues object interactions and achieve common functionality colleagues like all influence each other.
  4. Colleagues specific class (Concrete Colleague) role: is an abstract class that implements the colleague who, when you need to interact with other objects colleagues, by the intermediary object is responsible for subsequent interaction.


FIG intermediary model structure shown in Figure 1.
 

                 Mediator pattern configuration diagram

2. Mode of realization

The intermediary model codes are as follows:

package mediator;
import java.util.*;
public class MediatorPattern
{
    public static void main(String[] args)
    {
        Mediator md=new ConcreteMediator();
        Colleague c1,c2;
        c1=new ConcreteColleague1();
        c2=new ConcreteColleague2();
        md.register(c1);
        md.register(c2);
        c1.send();
        System.out.println("-------------");
        c2.send();
    }
}
//抽象中介者
abstract class Mediator
{
    public abstract void register(Colleague colleague);
    public abstract void relay(Colleague cl); //转发
}
//具体中介者
class ConcreteMediator extends Mediator
{
    private List<Colleague> colleagues=new ArrayList<Colleague>();
    public void register(Colleague colleague)
    {
        if(!colleagues.contains(colleague))
        {
            colleagues.add(colleague);
            colleague.setMedium(this);
        }
    }
    public void relay(Colleague cl)
    {
        for(Colleague ob:colleagues)
        {
            if(!ob.equals(cl))
            {
                ((Colleague)ob).receive();
            }   
        }
    }
}
//抽象同事类
abstract class Colleague
{
    protected Mediator mediator;
    public void setMedium(Mediator mediator)
    {
        this.mediator=mediator;
    }   
    public abstract void receive();   
    public abstract void send();
}
//具体同事类
class ConcreteColleague1 extends Colleague
{
    public void receive()
    {
        System.out.println("具体同事类1收到请求。");
    }   
    public void send()
    {
        System.out.println("具体同事类1发出请求。");
        mediator.relay(this); //请中介者转发
    }
}
//具体同事类
class ConcreteColleague2 extends Colleague
{
    public void receive()
    {
        System.out.println("具体同事类2收到请求。");
    }   
    public void send()
    {
        System.out.println("具体同事类2发出请求。");
        mediator.relay(this); //请中介者转发
    }
}

Operating results of the program are as follows: 

具体同事类1发出请求。
具体同事类2收到请求。
-------------
具体同事类2发出请求。
具体同事类1收到请求。

Mode of application examples

[Example 1] written intermediary model a "Shaoguan real estate exchange platform" program.

Description: Shaoguan Real Estate platform is the "real estate company" to the "Vendor Customer" and "buy-side clients' information exchange platform, more suitable for use intermediary model to achieve.

First, the definition of an intermediary company (Medium) interface, which is an abstract intermediary, it contains the customer registration method register (Customer member) and information forwarding method relay (String from, String ad) ; and then define a Shaoguan real estate (EstateMedium) the company, which is a specific mediator class that contains customer information stored List object, and implements the abstract method in the agency.

Then, the definition of a customer (Qistomer) class, which is an abstract colleagues class, which includes objects Mediator, and sending send information (String ad) receive a method of receiving information (String from, Stringad) interface method, since this procedure is window procedure, the present JPmme class inherits the class, and implements the action event processing method actionPerformed (ActionEvent e).

Finally, the definition of seller (Seller) category and buyer (Buyer) class, which are specific colleagues class is a subclass of the customer (Customer) class, which implements the abstract method in the parent class, the exchange of information through intermediaries like that configuration shown in Figure 2.
 

                Shaoguan block diagram of the real estate exchange platform


Code is as follows:

package mediator;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class DatingPlatform
{
    public static void main(String[] args)
    {
        Medium md=new EstateMedium();    //房产中介
        Customer member1,member2;
        member1=new Seller("张三(卖方)");
        member2=new Buyer("李四(买方)");
        md.register(member1); //客户注册
        md.register(member2);
    }
}
//抽象中介者:中介公司
interface Medium
{
    void register(Customer member); //客户注册
    void relay(String from,String ad); //转发
}
//具体中介者:房地产中介
class EstateMedium implements Medium
{
    private List<Customer> members=new ArrayList<Customer>();   
    public void register(Customer member)
    {
        if(!members.contains(member))
        {
            members.add(member);
            member.setMedium(this);
        }
    }   
    public void relay(String from,String ad)
    {
        for(Customer ob:members)
        {
            String name=ob.getName();
            if(!name.equals(from))
            {
                ((Customer)ob).receive(from,ad);
            }   
        }
    }
}
//抽象同事类:客户
abstract class Customer extends JFrame implements  ActionListener
{
    private static final long serialVersionUID=-7219939540794786080L;
    protected Medium medium;
    protected String name;   
    JTextField SentText;
    JTextArea ReceiveArea;   
    public Customer(String name)
    {
        super(name);
        this.name=name;       
    }
    void ClientWindow(int x,int y)
    {       
        Container cp;        
        JScrollPane sp;
        JPanel p1,p2;        
        cp=this.getContentPane();       
        SentText=new JTextField(18);
        ReceiveArea=new JTextArea(10,18);
        ReceiveArea.setEditable(false);
        p1=new JPanel();
        p1.setBorder(BorderFactory.createTitledBorder("接收内容:"));       
        p1.add(ReceiveArea);
        sp=new JScrollPane(p1);
        cp.add(sp,BorderLayout.NORTH);        
        p2=new JPanel();
        p2.setBorder(BorderFactory.createTitledBorder("发送内容:"));       
        p2.add(SentText);   
        cp.add(p2,BorderLayout.SOUTH);       
        SentText.addActionListener(this);       
        this.setLocation(x,y);
        this.setSize(250, 330);
        this.setResizable(false); //窗口大小不可调整
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);      
        this.setVisible(true);       
    }
    public void actionPerformed(ActionEvent e)
    {
        String tempInfo=SentText.getText().trim();
        SentText.setText("");
        this.send(tempInfo);
    }
    public String getName()
    {    return name;   }
    public void setMedium(Medium medium)
    {      this.medium=medium;  }   
    public abstract void send(String ad);
    public abstract void receive(String from,String ad);
}
//具体同事类:卖方
class Seller extends Customer
{
    private static final long serialVersionUID=-1443076716629516027L;
    public Seller(String name)
    {
        super(name);
        ClientWindow(50,100);
    }   
    public void send(String ad)
    {
        ReceiveArea.append("我(卖方)说: "+ad+"\n");
        //使滚动条滚动到最底端
        ReceiveArea.setCaretPosition(ReceiveArea.getText().length());
        medium.relay(name,ad);
    }
    public void receive(String from,String ad)
    {
        ReceiveArea.append(from +"说: "+ad+"\n");
        //使滚动条滚动到最底端
        ReceiveArea.setCaretPosition(ReceiveArea.getText().length());
    }
}
//具体同事类:买方
class Buyer extends Customer
{
    private static final long serialVersionUID = -474879276076308825L;
    public Buyer(String name)
    {
        super(name);
        ClientWindow(350,100);
    }   
    public void send(String ad)
    {
        ReceiveArea.append("我(买方)说: "+ad+"\n");
        //使滚动条滚动到最底端
        ReceiveArea.setCaretPosition(ReceiveArea.getText().length());
        medium.relay(name,ad);
    }
    public void receive(String from,String ad)
    {
          ReceiveArea.append(from +"说: "+ad+"\n");
        //使滚动条滚动到最底端
        ReceiveArea.setCaretPosition(ReceiveArea.getText().length());
    }
}

Running result of the program shown in Figure 3.
 

                       Shaoguan operating results of real estate exchange platform

Application of scene modes

Previous analysis of the structure and features of the intermediary model, which analyzes the scenarios below.

  • When there is a complex structural relationships between objects mesh dependence caused confusion and difficult to reuse.
  • When you want to create a run on objects between multiple classes, and do not want to generate a new subclass.

Extended mode

In the actual development, the following two methods usually employed to simplify the intermediary model the development easier.

  1. Interface intermediary is not defined, the specific object implementation as a single mediator embodiment.
  2. Colleagues object does not hold a mediator, but direct access to intermediaries who carry objects when needed and calls f.


Figure 4 is a simplified block diagram of the intermediary model.
 

                   Simplified block diagram of the intermediary model


Code is as follows:

package mediator;
import java.util.*;
public class SimpleMediatorPattern
{
    public static void main(String[] args)
    {
        SimpleColleague c1,c2;
        c1=new SimpleConcreteColleague1();
        c2=new SimpleConcreteColleague2();
        c1.send();
        System.out.println("-----------------");
        c2.send();
    }
}
//简单单例中介者
class SimpleMediator
{
    private static SimpleMediator smd=new SimpleMediator();   
    private List<SimpleColleague> colleagues=new ArrayList<SimpleColleague>();   
    private SimpleMediator(){}   
    public static SimpleMediator getMedium()
    {    return(smd);   }
    public void register(SimpleColleague colleague)
    {
        if(!colleagues.contains(colleague))
        {
            colleagues.add(colleague);
        }
    }
    public void relay(SimpleColleague scl)
    {       
        for(SimpleColleague ob:colleagues)
        {
            if(!ob.equals(scl))
            {
                ((SimpleColleague)ob).receive();
            }   
        }
    }
}
//抽象同事类
interface SimpleColleague
{
    void receive();   
    void send();
}
//具体同事类
class SimpleConcreteColleague1 implements SimpleColleague
{
    SimpleConcreteColleague1(){
        SimpleMediator smd=SimpleMediator.getMedium();
        smd.register(this);
    }
    public void receive()
    {    System.out.println("具体同事类1:收到请求。");    }   
    public void send()
    {
        SimpleMediator smd=SimpleMediator.getMedium();
        System.out.println("具体同事类1:发出请求...");
        smd.relay(this); //请中介者转发
    }
}
//具体同事类
class SimpleConcreteColleague2 implements SimpleColleague
{
    SimpleConcreteColleague2(){
        SimpleMediator smd=SimpleMediator.getMedium();
        smd.register(this);
    }
    public void receive()
    {    System.out.println("具体同事类2:收到请求。");    }   
    public void send()
    {
        SimpleMediator smd=SimpleMediator.getMedium();
        System.out.println("具体同事类2:发出请求...");
        smd.relay(this); //请中介者转发
    }
}

Program results are as follows: 

具体同事类1:发出请求...
具体同事类2:收到请求。
-----------------
具体同事类2:发出请求...
具体同事类1:收到请求。

 

Published 136 original articles · won praise 6 · views 1540

Guess you like

Origin blog.csdn.net/weixin_42073629/article/details/104437879