設計模式學習(二十三):中介模式

設計模式學習(二十三):中介模式

作者: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 圖

代碼

更多

設計模式學習專欄

參考資料