Click “like” to see, form a habit, the public account search [dime technology] pay attention to more original technical articles. This article has been included in GitHub org_Hejianhui /JavaStudy.

preface

  • 23 design modes for shorthand
  • The singleton pattern
  • Factory Method pattern
  • Abstract Factory pattern
  • The Builder/Builder pattern
  • Prototype mode
  • Flyweight mode
  • The facade pattern
  • Adapter mode
  • Decorator pattern
  • Observer mode
  • Strategy mode
  • Bridge mode
  • The Template Method pattern
  • The Chain of Responsibility model
  • Composite mode
  • Proxy mode
  • Memento mode
  • Command mode
  • State mode
  • Updates continue at……

Here are 23 design patterns to memorize quicklyThe mediator patternRelated content.

The schema definition

Define a mediation object that encapsulates the interactions between a set of objects, loosens the coupling between the original objects, and can change their interactions independently. Mediator mode is also called mediation mode, which is a typical application of Demeter’s rule.

The Law of Demeter (LoD) is also known as the Least Knowledge Principle (LKP), Born in 1987 as a Northeastern University research project called Demeter, proposed by Ian Holland and popularized by Booch, one of the founders of UML, He later became known as The Pragmatic Programmer in his classic book.

Demeter’s Law is defined as: Talk only to your immediate friends and not to strangers. The implication is that if two software entities do not communicate directly, then direct calls to each other should not occur and can be forwarded by a third party. Its purpose is to reduce the degree of coupling between classes and improve the relative independence of modules.

The “friend” in Demeter’s law refers to the current object itself, its member object, the object created by the current object, the method parameters of the current object, etc. These objects are associated, aggregated or combined with the current object, and can directly access the methods of these objects.

The template implementation is as follows:

package com.niuh.designpattern.mediator.v1;

import java.util.ArrayList;
import java.util.List;

/** * 

* Broker mode *

*/
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 mediator abstract class Mediator { public abstract void register(Colleague colleague); public abstract void relay(Colleague cl); / / forwarding } // Specific intermediaries 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 colleague class abstract class Colleague { protected Mediator mediator; public void setMedium(Mediator mediator) { this.mediator = mediator; } public abstract void receive(a); public abstract void send(a); } // Specific colleague class class ConcreteColleague1 extends Colleague { public void receive(a) { System.out.println("Request received for concrete colleague class 1."); } public void send(a) { System.out.println("Specific colleague class 1 makes a request."); mediator.relay(this); // Ask the intermediary to forward}}// Specific colleague class class ConcreteColleague2 extends Colleague { public void receive(a) { System.out.println("Specific colleague class 2 received the request."); } public void send(a) { System.out.println("Specific colleague class 2 makes a request."); mediator.relay(this); // Ask the intermediary to forward}}Copy the code

The results are as follows:

Specific Colleagues1Make a request. Specific Colleagues2Request received. ============== Specific colleague class2Make a request. Specific Colleagues1Request received.Copy the code

Problem solved

There are a large number of related relationships between objects, which will inevitably lead to the complex structure of the system. At the same time, if an object changes, we also need to track the objects associated with it and make corresponding processing at the same time.

Patterns of

The key to the realization of the mediator pattern is to identify the “mediator”.

To compose (a role). role
Mediator role It is an interface for intermediaries and provides abstract methods for registering and forwarding peer object information.
The ConcreteMediator role Implements a mediator interface that defines a List to manage colleague objects and coordinate interactions between various colleague roles, so it depends on the colleague role.
The Colleague role is abstract Define the interface of the colleague class, save the intermediary object, provide the abstract method of the interaction of the colleague object, and implement all the common functions of the interaction of the colleague class.
Concrete Colleague roles Is the implementer of the abstract colleague class, and the intermediary object is responsible for subsequent interactions when it needs to interact with other colleague objects.

Example is given to illustrate

Instance profiles

Use intermediary mode to write a “Beijing real estate exchange platform” program.

Analysis: Beijing real estate exchange platform is a platform for “real estate intermediary companies” to provide “seller customers” and “buyer customers” to exchange information, which is more suitable for the intermediary model to achieve.

Using the step

Step 1: Define a 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).

interface Medium {
    // Customer registration
    void register(Customer member);

    / / forwarding
    void relay(String from, String ad);
}
Copy the code

Step 2: Define a Beijing real estate agency (EstateMedium), which is a concrete intermediary class that contains List objects to store customer information and implements abstract methods in the agency.

// Intermediary: real estate agent
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); }}}}Copy the code

Step 3: Define a client (Qistomer) class, which is an abstract colleague class, which contains the intermediary object, and send(String AD) method to send information and receive(String from, Stringad) method interface, because this program is a form program, So this class inherits the JPmme class and implements actionPerformed(ActionEvent E).

// Abstract colleague class: customer
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("Received contents:"));
        p1.add(ReceiveArea);
        sp = new JScrollPane(p1);
        cp.add(sp, BorderLayout.NORTH);
        p2 = new JPanel();
        p2.setBorder(BorderFactory.createTitledBorder("Send content:"));
        p2.add(SentText);
        cp.add(p2, BorderLayout.SOUTH);
        SentText.addActionListener(this);
        this.setLocation(x, y);
        this.setSize(250.330);
        this.setResizable(false); // The window size cannot be adjusted
        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(a) {
        return name;
    }

    public void setMedium(Medium medium) {
        this.medium = medium;
    }

    public abstract void send(String ad);

    public abstract void receive(String from, String ad);
}
Copy the code

Step 4: Define the Seller and Buyer classes, which are concrete colleague classes and subclasses of the Customer class that implement abstract methods in the parent class and communicate information through the intermediary class.

// Specific colleague category: seller
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("I (the seller) say:" + ad + "\n");
        // Make the scroll bar scroll to the bottom
        ReceiveArea.setCaretPosition(ReceiveArea.getText().length());
        medium.relay(name, ad);
    }

    public void receive(String from, String ad) {
        ReceiveArea.append(from + "Say:" + ad + "\n");
        // Make the scroll bar scroll to the bottomReceiveArea.setCaretPosition(ReceiveArea.getText().length()); }}// Specific colleague class: buyer
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("I (the buyer) say:" + ad + "\n");
        // Make the scroll bar scroll to the bottom
        ReceiveArea.setCaretPosition(ReceiveArea.getText().length());
        medium.relay(name, ad);
    }

    public void receive(String from, String ad) {
        ReceiveArea.append(from + "Say:" + ad + "\n");
        // Make the scroll bar scroll to the bottomReceiveArea.setCaretPosition(ReceiveArea.getText().length()); }}Copy the code

The output

advantages

  1. The coupling between objects is reduced, making objects easy to be reused independently.
  2. The one-to-many association between objects is changed into one-to-one association, which improves the flexibility of the system and makes the system easy to maintain and expand.

disadvantages

When there are too many colleague classes, the responsibility of the mediator becomes large, and it becomes so complex and large that the system becomes difficult to maintain.

Application scenarios

  • When there is a complex network structure between objects, the dependency relationship is chaotic and difficult to reuse.
  • When you want to create an object that runs between classes without generating new subclasses.

Schema extension

In actual development, the following two approaches are commonly used to simplify the mediator pattern and make development easier.

  1. The concrete mediator object is implemented as a singleton without defining the mediator interface.
  2. The peer object does not hold the mediator, but rather gets the mediator object directly and calls it when needed.

The program code is as follows:

package com.niuh.designpattern.mediator.v3;

import java.util.ArrayList;
import java.util.List;

/** * 

* Simplifies the broker pattern *

*/
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(); }}// simple singleton mediator class SimpleMediator { private static SimpleMediator smd = new SimpleMediator(); private List<SimpleColleague> colleagues = new ArrayList<SimpleColleague>(); private SimpleMediator(a) {}public static SimpleMediator getMedium(a) { 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(); }}}}// Abstract colleague class interface SimpleColleague { void receive(a); void send(a); } // Specific colleague class class SimpleConcreteColleague1 implements SimpleColleague { SimpleConcreteColleague1() { SimpleMediator smd = SimpleMediator.getMedium(); smd.register(this); } public void receive(a) { System.out.println("Concrete Colleague Class 1: Request received."); } public void send(a) { SimpleMediator smd = SimpleMediator.getMedium(); System.out.println("Concrete Colleague Class 1: Making a request..."); smd.relay(this); // Ask the intermediary to forward}}// Specific colleague class class SimpleConcreteColleague2 implements SimpleColleague { SimpleConcreteColleague2() { SimpleMediator smd = SimpleMediator.getMedium(); smd.register(this); } public void receive(a) { System.out.println("Specific Colleague Type 2: Request received."); } public void send(a) { SimpleMediator smd = SimpleMediator.getMedium(); System.out.println("Concrete Colleague Class 2: Making a request..."); smd.relay(this); // Ask the intermediary to forward}}Copy the code

The following output is displayed:

Specific Colleagues1: Make a request... Specific Colleagues2: The request was received. ============== Specific colleague class2: Make a request... Specific Colleagues1: The request was received.Copy the code

Application in source code

java.util.Timer
java.util.concurrent.Executer#execute()
java.util.concurrent.ExecuterService#submit()
java.lang.reflect.Method#invoke()
Copy the code

PS: The above code is submitted to Github: github.com/Niuh-Study/…

GitHub Org_Hejianhui /JavaStudy GitHub Hejianhui /JavaStudy