Design pattern - mediator pattern

1, Basic introduction

  • English Name: Mediator
  • Concept: encapsulate a series of object interactions with a mediation object. The mediator makes the objects interact without display, so that their coupling is loose, and the interaction between them can be changed independently
  • Mode type: structural
  • Design principle:
  • Main features: a class is only responsible for handling its own activities (behaviors), and activities unrelated to itself are left to the intermediary for processing

2, Realize

Requirements:

  • Simulate the interaction of three modules of purchase, sales and inventory

1. General implementation

  • Each class is associated with the other two classes
I. code
purchasing management
public class Purchase {

    //Buy IBM computers
    public void buyIBMcomputer(int number) {
        // Access inventory
        Stock stock = new Stock();
        //Visit sales
        Sale sale = new Sale();
        //Computer sales
        int saleStatus = sale.getSaleStatus();
        if (saleStatus > 80) {
            //Good sales
            System.out.println("purchase IBM computer:" + number + "platform");
            stock.increase(number);
        } else {
            //Poor sales
            int buyNumber = number / 2;
            //Half purchase
            System.out.println("purchase IBM computer:" + buyNumber + "platform");
        }
    }

    //No longer purchase IBM computers
    public void refuseBuyIBM() {
        System.out.println("No longer purchase IBM computer");
    }
}
Inventory management
public class Stock {

    //At first there were 100 computers
    private static int COMPUTER_NUMBER = 100;

    //Inventory increase
    public void increase(int number) {
        COMPUTER_NUMBER = COMPUTER_NUMBER + number;
        System.out.println("The inventory quantity is:" + COMPUTER_NUMBER);
    }

    //Inventory reduction
    public void decrease(int number) {
        COMPUTER_NUMBER = COMPUTER_NUMBER - number;
        System.out.println("The inventory quantity is:" + COMPUTER_NUMBER);
    }

    //Get inventory quantity
    public int getStockNumber() {
        return COMPUTER_NUMBER;
    }

    //When the inventory pressure is high, the buyer should be informed not to purchase, and the salesperson should sell as soon as possible
    public void clearStock() {
        Purchase purchase = new Purchase();
        Sale sale = new Sale();
        System.out.println("The quantity of inventory to be cleared is:" + COMPUTER_NUMBER);
        //Ask for discount sales
        sale.offSale();
        //Ask the purchaser not to purchase
        purchase.refuseBuyIBM();
    }
}
Sales management
public class Sale {
    //Selling IBM computers
    public void sellIBMComputer(int number) {
        //Access inventory
        Stock stock = new Stock();
        //Access purchasing
        Purchase purchase = new Purchase();
        if (stock.getStockNumber() < number) {
            //Insufficient inventory for sale
            purchase.buyIBMcomputer(number);
        }
        System.out.println("sale IBM computer" + number + "platform");
        stock.decrease(number);
    }

    //Feedback the sales situation. It changes from 0 to 100. 0 means no one sells at all. 100 means very popular. Sell one by one
    public int getSaleStatus() {
        Random rand = new Random(System.currentTimeMillis());
        int saleStatus = rand.nextInt(100);
        System.out.println("IBM The sales of computers are:" + saleStatus);
        return saleStatus;
    }

    //Discount treatment
    public void offSale() {
        //How much is there in the warehouse
        Stock stock = new Stock();
        System.out.println("Discount sales IBM computer" + stock.getStockNumber() + "platform");
    }
}
scene
public class Client {
    public static void main(String[] args) {
        //Purchasing personnel purchase computers
        System.out.println("------Purchasing personnel purchase computers--------");
        Purchase purchase = new Purchase();
        purchase.buyIBMcomputer(100);
        //The salesperson sells computers
        System.out.println("\n------The salesperson sells computers--------");
        Sale sale = new Sale();
        sale.sellIBMComputer(1);
        //Warehouse management personnel manage inventory
        System.out.println("\n------Warehouse management personnel shall clear the warehouse--------");
        Stock stock = new Stock();
        stock.clearStock();
    }
}
II. Advantages
III. disadvantages

2. Pattern

  • Mediator Abstract mediator role
    • The abstract mediator role defines a unified interface for communication between colleague roles
  • Concrete Mediator role
    • The specific mediator role realizes the cooperative behavior by coordinating the roles of colleagues, so it must rely on the roles of colleagues
  • Collague Colleague role
    • Every colleague role knows the intermediary role, and when communicating with other colleague roles, we must cooperate through the intermediary role.
    • The behaviors of each colleague class are divided into two types:
      • One is the behavior of colleagues themselves, such as changing the state of the object itself and dealing with their own behavior. This behavior is called self method, which has no dependence on other colleagues or intermediaries;
      • The second is the behavior that can only be completed by relying on intermediaries, which is called dep method
I. code

Abstract mediator

public abstract class AbstractMediator {
    protected Purchase purchase;
    protected Sale sale;
    protected Stock stock;

    //Constructor
    public AbstractMediator() {
        purchase = new Purchase(this);
        sale = new Sale(this);
        stock = new Stock(this);
    }

    //The most important method for mediators is called event method, which deals with the relationship between multiple objects
    public abstract void execute(String str, Object... objects);
}
Specific intermediary
public class Mediator extends AbstractMediator {

    @Override
    public void execute(String str, Object... objects) {
        if (str.equals("purchase.buy")) { //Purchase computer
            this.buyComputer((Integer) objects[0]);
        } else if (str.equals("sale.sell")) {
            //Selling computers
            this.sellComputer((Integer) objects[0]);
        } else if (str.equals("sale.offsell")) {
            //Discount sales
            this.offSell();
        } else if (str.equals("stock.clear")) {
            //Clearing treatment
            this.clearStock();
        }
    }

    //Purchase computer
    private void buyComputer(int number) {
        int saleStatus = super.sale.getSaleStatus();
        if (saleStatus > 80) {
            //Good sales
            System.out.println("purchase IBM computer:" + number + "platform");
            super.stock.increase(number);
        } else {
            //Poor sales
            int buyNumber = number / 2;
            //Half purchase
            System.out.println("purchase IBM computer:" + buyNumber + "platform");
        }
    }

    //Selling computers
    private void sellComputer(int number) {
        if (super.stock.getStockNumber() < number) {
            //Insufficient inventory for sale
            super.purchase.buyIBMcomputer(number);
        }
        super.stock.decrease(number);
    }

    //Discount sales Computer
    private void offSell() {
        System.out.println("Discount sales IBM computer" + stock.getStockNumber() + "platform");
    }

    //Clearing treatment
    private void clearStock() {
        //Request clearance sales
        super.sale.offSale();
        //Ask the purchaser not to purchase
        super.purchase.refuseBuyIBM();
    }
}
Abstract colleague class
public abstract class AbstractColleague {
    protected AbstractMediator mediator;

    public AbstractColleague(AbstractMediator _mediator) {
        this.mediator = _mediator;
    }
}
purchasing management
public class Purchase extends AbstractColleague {
    public Purchase(AbstractMediator _mediator) {
        super(_mediator);
    }

    //Buy IBM computers
    public void buyIBMcomputer(int number) {
        super.mediator.execute("purchase.buy", number);
    }

    //No longer purchase IBM computers
    public void refuseBuyIBM() {
        System.out.println("No longer purchase IBM computer");
    }
}
Sales management
public class Sale extends AbstractColleague {

    public Sale(AbstractMediator _mediator) {
        super(_mediator);
    }

    //Selling IBM computers
    public void sellIBMComputer(int number) {
        super.mediator.execute("sale.sell", number);
        System.out.println("sale IBM computer" + number + "platform");
    }

    //Feedback the sales situation. It changes from 0 to 100. 0 means no one sells at all. 100 means very popular. Sell one by one
    public int getSaleStatus() {
        Random rand = new Random(System.currentTimeMillis());
        int saleStatus = rand.nextInt(100);
        System.out.println("IBM The sales of computers are:" + saleStatus);
        return saleStatus;
    }

    //Discount treatment
    public void offSale() {
        super.mediator.execute("sale.offsell");
    }
}
Inventory management
public class Stock extends AbstractColleague {

    public Stock(AbstractMediator _mediator) {
        super(_mediator);
    }

    //At first there were 100 computers
    private static int COMPUTER_NUMBER = 100;

    //Inventory increase
    public void increase(int number) {
        COMPUTER_NUMBER = COMPUTER_NUMBER + number;
        System.out.println("The inventory quantity is:" + COMPUTER_NUMBER);
    }

    //Inventory reduction
    public void decrease(int number) {
        COMPUTER_NUMBER = COMPUTER_NUMBER - number;
        System.out.println("The inventory quantity is:" + COMPUTER_NUMBER);
    }

    //Get inventory quantity
    public int getStockNumber() {
        return COMPUTER_NUMBER;
    }

    //When the inventory pressure is high, it is necessary to inform the purchaser not to purchase and the salesperson to sell as soon as possible
    public void clearStock() {
        System.out.println("The quantity of inventory to be cleared is:" + COMPUTER_NUMBER);
        super.mediator.execute("stock.clear");
    }
}
scene
public class Client {

    public static void main(String[] args) {
        AbstractMediator mediator = new Mediator();
        //Purchasing personnel purchase computers
        System.out.println("------Purchasing personnel purchase computers--------");
        Purchase purchase = new Purchase(mediator);
        purchase.buyIBMcomputer(100);
        //The salesperson sells computers
        System.out.println("\n------The salesperson sells computers--------");
        Sale sale = new Sale(mediator);
        sale.sellIBMComputer(1);
        //Warehouse management personnel manage inventory
        System.out.println("\n------Warehouse management personnel shall clear the warehouse--------");
        Stock stock = new Stock(mediator);
        stock.clearStock();
    }
}
II. Advantages
  • A mediator is added to the scene class, and then passed to three colleague classes respectively. The three classes have the same characteristics: they are only responsible for processing their own activities (behaviors), and activities unrelated to them are lost to the mediator for processing. The results of program operation are the same.

  • In terms of project design, with the addition of intermediaries, the design structure is much clearer, the coupling between classes is greatly reduced, and the code quality has been greatly improved.

  • In the case of multiple object dependencies, by adding the role of mediator, the association or dependency of multiple objects is cancelled and the coupling of objects is reduced

III. disadvantages
  • Mediators will expand greatly, and the logic is complex. The direct interdependence of N objects is transformed into the dependency between mediators and colleagues. The more colleagues, the more complex the logic of mediators

3, Usage scenario

  • It is applicable to the tight coupling between multiple objects. The standard of tight coupling is that there is a spider mesh structure in the class diagram
    • We must consider using the intermediary model, which is conducive to combing the spider web into a star structure, making the originally complex and chaotic relationship clear and simple
  • N objects have mutual dependencies (n > 2)
  • Multiple objects have dependencies, but the dependent behavior is uncertain or may change. In this case, it is generally recommended to adopt the mediator model to reduce the risk diffusion caused by change.
  • Product development. An obvious example is the MVC framework. Applying the intermediary model to the product can improve the performance and scalability of the product, but it is not necessary for the project development, because the project aims at delivery and production, while the product aims at stability, efficiency and expansion.

1. Common application scenarios

I. MVC framework
  • MVC framework, in which C (Controller) is an intermediary, called front Controller. Its role is to isolate M(Model, business logic) and V (View), coordinate the collaborative work of M and V, integrate the results of M operation and the View represented by V into a page that can be displayed by the front end, and reduce the dependency between M and V.

Keywords: Design Pattern

Added by aztec on Mon, 20 Dec 2021 23:04:07 +0200