Design Patterns (19): Behavioral Intermediary Patterns

Design Patterns Series Articles

Design Patterns (1): Creational Singleton Patterns

Design Patterns (2, 3): Creational Factory Methods and Abstract Factory Patterns

Design Patterns (4): Creational Prototype Patterns

Design Pattern (5): Creational Builder Pattern

Design Pattern (6): Structural Agent Pattern

Design Pattern (7): Structural Adapter Pattern

Design Pattern (8): Structural Decorator Pattern

Design Pattern (9): Structural Bridge Pattern

Design Patterns (10): Structural Appearance Patterns

Design Patterns (11): Structural Combination Patterns

Design Pattern (12): Structural Flyweight Pattern

Design Pattern (13): Behavioral Template Method Pattern

Design Patterns (14): Behavioral Strategy Patterns

Design Patterns (15): Behavioral Command Patterns

Design Pattern (16): Behavioral Chain of Responsibility Pattern

Design Patterns (17): Behavioral State Patterns

Design Pattern (18): Behavioral Observer Pattern

Design Patterns (19): Behavioral Intermediary Patterns



1. Classification of Design Patterns

  • Creational patterns
    • Used to describe "how to create objects", its main feature is "separation of object creation and use"
    • Provides singletons, prototypes, factory methods, abstract factories, and builders 5 种创建型模式
  • structural pattern
    • Used to describe how to organize classes or objects into larger structures in a certain layout
    • Proxy, Adapter, Bridge, Decorator, Facade, Flyweight, Composition are provided 7 种结构型模式
  • behavioral model
    • Used to describe how classes or objects cooperate with each other to complete tasks that a single object cannot do alone, and how to assign responsibilities
    • Provides template methods, policies, commands, chain of responsibility, state, observers, mediators, iterators, visitors, mementos, interpreters 11 种行为型模式

2. Intermediary model

1 Overview

  • The relationship between colleague classes is relatively complicated. When multiple colleague classes are related to each other, the relationship between them will appear as a complex network structure
  • For example, in the left picture below, there are six colleagues class objects, if object 1 changes, then 4 objects will be affected
  • If the intermediary mode is introduced, you can see from the figure on the right below that any change in a class will only affect the class itself and the intermediary

insert image description here

definition

  • Define an intermediary role to encapsulate the interaction between a series of objects
  • Make the coupling between the original objects loose, and the interaction between them can be changed independently

2. Structure

The Mediator pattern contains the following main roles:

  • Abstract mediator (Mediator) role: it is the interface of the mediator, providing an abstract method for registering and forwarding the information of colleague objects
  • Specific mediator (ConcreteMediator) role: implement the mediator interface, define a List to manage colleague objects, and coordinate the interaction between each colleague role, so it depends on the colleague role
  • Abstract colleague class (Colleague) role: define the interface of the colleague class, save the intermediary object, provide an abstract method for interacting with the colleague object, and realize the public functions of all the colleague classes that affect each other
  • Concrete Colleague role: It is the implementer of the abstract colleague class. When interacting with other colleague objects, the intermediary object is responsible for the subsequent interaction

3. Realize

[Example] Renting a house

  • Now renting a house is basically through a housing intermediary, and the homeowner entrusts the house to the housing intermediary
  • Renters obtain housing information from housing agents
  • A real estate agent acts as a bridge between renters and homeowners中介者

The class diagram is as follows:

insert image description here
code show as below:

  • abstract mediator
public abstract class Mediator {
    
    
    //申明一个联络方法
    public abstract void constact(String message,Person person);
}
  • abstract colleague class
public abstract class Person {
    
    
    protected String name;
    protected Mediator mediator;

    public Person(String name,Mediator mediator){
    
    
        this.name = name;
        this.mediator = mediator;
    }
}
  • Specific colleagues
  • The constructor aggregates specific intermediaries, and both the landlord and the tenant need to contact the intermediary
//具体同事类 房屋拥有者
public class HouseOwner extends Person {
    
    

    public HouseOwner(String name, Mediator mediator) {
    
    
        super(name, mediator);
    }

    //与中介者联系
    public void constact(String message){
    
    
        mediator.constact(message, this);
    }

    //获取信息
    public void getMessage(String message){
    
    
        System.out.println("房主:[" + name + "] 获取到的信息是:【" + message + "】");
    }
}

//具体同事类 租房者
public class Tenant extends Person {
    
    
    public Tenant(String name, Mediator mediator) {
    
    
        super(name, mediator);
    }

    //与中介者联系
    public void constact(String message){
    
    
        mediator.constact(message, this);
    }

    //获取信息
    public void getMessage(String message){
    
    
        System.out.println("租房者:[" + name + "] 获取到的信息是:【" + message + "】");
    }
}
  • Agency
  • Agents bring together renters and homeowners
public class MediatorStructure extends Mediator {
    
    
    //首先中介结构必须知道所有房主和租房者的信息
    private HouseOwner houseOwner;
    private Tenant tenant;

    public HouseOwner getHouseOwner() {
    
    
        return houseOwner;
    }

    public void setHouseOwner(HouseOwner houseOwner) {
    
    
        this.houseOwner = houseOwner;
    }

    public Tenant getTenant() {
    
    
        return tenant;
    }

    public void setTenant(Tenant tenant) {
    
    
        this.tenant = tenant;
    }

	@Override
    public void constact(String message, Person person) {
    
    
        if (person == houseOwner) {
    
      //如果是房主,则租房者获得信息
            tenant.getMessage(message);
        } else {
    
                         //反正则是房主获得信息
            houseOwner.getMessage(message);
        }
    }
}
  • test class
  • After the landlord and tenant contact the intermediary, the intermediary will judge
    • If issued by the landlord, the intermediary forwards it to the tenant
    • If issued by the tenant, the agent forwards it to the landlord
public class Client {
    
    
    public static void main(String[] args) {
    
    
        //一个房主、一个租房者、一个中介机构
        MediatorStructure mediator = new MediatorStructure();

        //房主和租房者只需要知道中介机构即可
        HouseOwner houseOwner = new HouseOwner("张三", mediator);
        Tenant tenant = new Tenant("李四", mediator);

        //中介结构要知道房主和租房者
        mediator.setHouseOwner(houseOwner);
        mediator.setTenant(tenant);

        tenant.constact("需要租三室的房子");
        houseOwner.constact("我这有三室的房子,你需要租吗?");
    }
}

输出结果:

房主:[张三] 获取到的信息是:【我要租三室的房子!!!】
租房者:[李四] 获取到的信息是:【我这里有三室的房子,你要租吗?】

4. Advantages and disadvantages

advantage

  • loose coupling
    • The mediator pattern encapsulates the interaction between multiple colleague objects into the mediator object
    • So that the loose coupling between colleagues objects can basically achieve complementary dependencies
    • In this way, colleagues objects can be changed and reused independently, instead of "moving the whole body by pulling one place" as before
  • centralized control interaction
    • The interaction of multiple colleague objects is encapsulated in the intermediary object for centralized management
    • When these interactive behaviors change, you only need to modify the intermediary object
    • Of course, if it is a well-made system, then the intermediary object is extended, and each colleague class does not need to be modified
  • Convert one-to-many association to one-to-one association
    • When the intermediary pattern is not used, the relationship between colleague objects is usually one-to-many
    • After introducing the mediator object, the relationship between the mediator object and the colleague object usually becomes a two-way one-to-one

shortcoming

  • When there are too many coworker classes, the responsibility of the mediator will be large, and it will become complex and large, so that the system is difficult to maintain

5. Usage scenarios

  • There are complex reference relationships between objects in the system, and the system structure is confusing and difficult to understand
  • When you want to create an object that runs between multiple classes, but don't want to generate new subclasses

Guess you like

Origin blog.csdn.net/qq_35512802/article/details/131235321