中介者模式透過獨立的物件來協調物件之間的互動行為,避免它們相互依賴。
想像你在一間公司,各部門都透過專案管理組來進行溝通。每當某個部門有需求時,都會聯絡專案管理組,再由產品負責人協調相關人員做出回應。專案管理組就像是中介者,根據客戶的需求聯繫相關人員解決問題。
這樣的好處是,客戶不需要了解公司內部的運作細節,而各部門之間的工作也變得更有條理,減少了混亂和無效的溝通。
在多人聊天室中,每個使用者都可以傳送訊息給其他使用者。假如使用者必須指名訊息的發送對象,掌握其他使用者的登入狀態,這個系統會變得過於複雜。我們可以使用中介者模式來設計聊天室,讓中介者複雜接收和轉發訊息,簡化使用者之間的互動。
這個類別代表聊天室的使用者,每個使用者可以發送和接收訊息。當使用者發送訊息時,訊息會經過中介者 ChatRoom
傳遞給其他使用者。
class User {
constructor(private chatRoom: ChatRoom, public name: string) {}
sendMessage(message: string) {
this.chatRoom.messageReceived(message, this);
}
receiveMessage(message: string, sender: User) {
console.log(
`${this.name} received message from ${sender.name}: ${message}`
);
}
}
ChatRoom
類別是中介者,負責協調和管理多個使用者之間的訊息傳遞。當某個使用者發送訊息時,中介者會確保其他使用者接收到該訊息。
class ChatRoom {
private users: User[] = [];
addUser(user: User) {
this.users.push(user);
}
messageReceived(message: string, sender: User) {
console.log(`${sender.name} sent message: ${message}`);
this.users.forEach((user) => {
if (user !== sender) {
user.receiveMessage(message, sender);
}
});
}
}
我們模擬了聊天室的運作,創建一個聊天室並加入三位使用者,然後模擬他們之間的訊息傳遞。
class ChatRoomTestDrive {
static main() {
const chatRoom = new ChatRoom();
const user1 = new User(chatRoom, "Evans");
const user2 = new User(chatRoom, "Howard");
const user3 = new User(chatRoom, "Judy");
chatRoom.addUser(user1);
chatRoom.addUser(user2);
chatRoom.addUser(user3);
user1.sendMessage("Hello, everyone!");
user2.sendMessage("Hi, Evans!");
user2.sendMessage("Want to meet this weekend?");
}
}
ChatRoomTestDrive.main();
輸出結果。
Evans has joined the chat.
Howard has joined the chat.
Judy has joined the chat.
Evans sent message: Hello, everyone!
Howard received message from Evans: Hello, everyone!
Judy received message from Evans: Hello, everyone!
Howard sent message: Hi, Evans!
Evans received message from Howard: Hi, Evans!
Judy received message from Howard: Hi, Evans!
Howard sent message: Anyone want to drink tonight?
Evans received message from Howard: Anyone want to drink tonight?
Judy received message from Howard: Anyone want to drink tonight?
Judy sent message: Always have time for a drink!
Evans received message from Judy: Always have time for a drink!
Howard received message from Judy: Always have time for a drink!
中介者模式包含三個角色:
在中介者模式中,物件不會直接溝通,而是透過中介者發送與接收訊息。中介者根據收到的訊息協調其他物件執行任務,從而避免物件之間直接互動。這不僅降低了耦合性,還讓物件的職責更為單一,從而提升了它們的重用性。我們可以透過替換中介者來改變物件行為,而無需修改程式碼,以靈活應對不同情境