[Design Pattern] 20, Intermediary Pattern

(20) Intermediary Model

The Mediator Pattern refers to the realization of access between systems through an intermediary object, so that the objects in the system do not need to interact explicitly, so as to achieve decoupling.

1. Design principles of the mediator model

1. Abstract Mediator: Define an abstract unified interface;

2. Concrete Mediator: Processes specific object information;

3. Colleague: each colleague needs to rely on the role of mediator to communicate with other colleagues;

4, specific colleagues (ConcreateColleague): responsible for the realization of spontaneous behavior.

image-20210319100850819

2. Simple example

The chat room isolates each chat object, which is the embodiment of an intermediary.

public class User {
    
    
    private String name;
    private ChatRoom chatRoom;

    public User(String name, ChatRoom chatRoom) {
    
    
        this.name = name;
        this.chatRoom = chatRoom;
    }

    public String getName() {
    
    
        return name;
    }

    //    用户直接和聊天室绑定了
    public void sendMessage(String msg) {
    
    
        this.chatRoom.showMsg(this, msg);
    }
}
public class ChatRoom {
    
    
//    聊天室方法展示聊天用户和消息
    public void showMsg(User user,String msg){
    
    
        System.out.println("["+user.getName()+"]:"+msg);
    }
}
public class Client {
    
    
    public static void main(String[] args) {
    
    
        ChatRoom room = new ChatRoom();
        User alice = new User("alice",room);
        User bob = new User("bob",room);

        alice.sendMessage("hi,i am alice,bob!");
        bob.sendMessage("hi,this is bob!");
    }
}

3. Comments on the intermediary model

The mediator pattern can realize the decoupling between classes, and each class performs its own duties. However, when there are many classes, the mediator will become bloated and the system complexity will increase.

Guess you like

Origin blog.csdn.net/qq_40589204/article/details/118511893