设计模式学习(二十三):中介模式

设计模式学习(二十三):中介模式

作者:Grey

原文地址:

博客园:设计模式学习(二十三):中介模式

CSDN:设计模式学习(二十三):中介模式

中介模式

中介模式是一种行为型模式。

举个简单的例子,如果一个聊天室里面的用户1和用户2要聊天,聊天室就相当于中介的地位,用户1和用户2只管调用发消息方法,聊天室即可把消息给对方

public class ChatRoom {
    public static void showMessage(User user, String content) {
        System.out.println("user :" + user.getName() + " send a message, content is " + content);
    }
}

以上代码表示,聊天室将 user 说的 content 展示出来

主方法只需要如下调用即可:

public class Main {
    public static void main(String[] args) {
        User user = new User("Peter");
        user.sendMessage("Hello ");
        user = new User("Harry");
        user.sendMessage("Hi");
    }
}

User 中的 sendMessage 方法

public void sendMessage(String content){ChatRoom.showMessage(this,content);}

上述示例的 UML 图如下

image

中介模式应用

  • JDK 中的 Timer.schedule()

UML 和 代码

UML 图

代码

更多

设计模式学习专栏

参考资料