元素码农
基础
UML建模
数据结构
算法
设计模式
网络
TCP/IP协议
HTTPS安全机制
WebSocket实时通信
数据库
sqlite
postgresql
clickhouse
后端
rust
go
java
php
mysql
redis
mongodb
etcd
nats
zincsearch
前端
浏览器
javascript
typescript
vue3
react
游戏
unity
unreal
C++
C#
Lua
App
android
ios
flutter
react-native
安全
Web安全
测试
软件测试
自动化测试 - Playwright
人工智能
Python
langChain
langGraph
运维
linux
docker
工具
git
svn
🌞
🌙
目录
▶
设计原则
单一职责原则
开闭原则
里氏替换原则
依赖倒置原则
接口隔离原则
迪米特法则
▶
创建型模式
工厂方法模式
抽象工厂
单例模式
建造者模式
原型模式
▶
结构型模式
适配器模式
装饰器模式
代理模式
外观模式
组合模式
桥接模式
享元模式
▶
行为型模式
策略模式
观察者模式
命令模式
模板方法模式
状态模式
责任链模式
迭代器模式
中介者模式
访问者模式
备忘录模式
解释器模式
发布时间:
2025-03-21 15:22
↑
☰
# 中介者模式 ## 概述 中介者模式(Mediator Pattern)是一种行为型设计模式,它通过一个中介对象来封装一系列对象之间的交互。中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。 ## 问题场景 在软件开发中,我们经常会遇到以下场景: 1. 对象之间存在复杂的交互关系 2. 对象之间的耦合度过高 3. 系统中对象需要频繁地相互通信 ## 解决方案 中介者模式通过以下方式解决这些问题: ```mermaid classDiagram class Mediator { <<interface>> +notify(sender, event) } class ConcreteMediator { -componentA: Component -componentB: Component +notify(sender, event) } class Component { -mediator: Mediator +setMediator(Mediator) } class ConcreteComponentA { +operationA() } class ConcreteComponentB { +operationB() } Mediator <|.. ConcreteMediator Component <|-- ConcreteComponentA Component <|-- ConcreteComponentB ConcreteMediator --> ConcreteComponentA ConcreteMediator --> ConcreteComponentB ``` 主要角色: 1. 中介者(Mediator): 定义一个接口用于与各同事对象通信 2. 具体中介者(ConcreteMediator): 实现中介者接口,协调各同事对象 3. 同事类(Colleague): 知道中介者对象,与其他同事对象通过中介者通信 ## 代码示例 ### 1. 基本实现 ```go // Mediator 中介者接口 type Mediator interface { Notify(sender Component, event string) string } // Component 组件接口 type Component interface { SetMediator(mediator Mediator) } // BaseComponent 基础组件 type BaseComponent struct { mediator Mediator } func (c *BaseComponent) SetMediator(mediator Mediator) { c.mediator = mediator } // ConcreteComponentA 具体组件A type ConcreteComponentA struct { BaseComponent } func NewConcreteComponentA() *ConcreteComponentA { return &ConcreteComponentA{} } func (c *ConcreteComponentA) OperationA() string { return c.mediator.Notify(c, "A") } // ConcreteComponentB 具体组件B type ConcreteComponentB struct { BaseComponent } func NewConcreteComponentB() *ConcreteComponentB { return &ConcreteComponentB{} } func (c *ConcreteComponentB) OperationB() string { return c.mediator.Notify(c, "B") } // ConcreteMediator 具体中介者 type ConcreteMediator struct { componentA *ConcreteComponentA componentB *ConcreteComponentB } func NewConcreteMediator(componentA *ConcreteComponentA, componentB *ConcreteComponentB) *ConcreteMediator { mediator := &ConcreteMediator{ componentA: componentA, componentB: componentB, } componentA.SetMediator(mediator) componentB.SetMediator(mediator) return mediator } func (m *ConcreteMediator) Notify(sender Component, event string) string { switch event { case "A": return "Mediator reacts on A and triggers following operations:\n" + "Component B operation" case "B": return "Mediator reacts on B and triggers following operations:\n" + "Component A operation" } return "" } ``` ### 2. 实际应用示例 ```go // 以聊天室为例 // ChatRoom 聊天室中介者接口 type ChatRoom interface { SendMessage(message string, user User) string AddUser(user User) } // User 用户接口 type User interface { Send(message string) string Receive(message string) string GetName() string SetChatRoom(room ChatRoom) } // ChatUser 聊天用户 type ChatUser struct { name string chatRoom ChatRoom } func NewChatUser(name string) *ChatUser { return &ChatUser{name: name} } func (u *ChatUser) Send(message string) string { return u.chatRoom.SendMessage(message, u) } func (u *ChatUser) Receive(message string) string { return fmt.Sprintf("%s received: %s", u.name, message) } func (u *ChatUser) GetName() string { return u.name } func (u *ChatUser) SetChatRoom(room ChatRoom) { u.chatRoom = room } // ConcreteChatRoom 具体聊天室 type ConcreteChatRoom struct { users []User } func NewConcreteChatRoom() *ConcreteChatRoom { return &ConcreteChatRoom{ users: make([]User, 0), } } func (r *ConcreteChatRoom) AddUser(user User) { user.SetChatRoom(r) r.users = append(r.users, user) } func (r *ConcreteChatRoom) SendMessage(message string, user User) string { result := fmt.Sprintf("%s sends: %s\n", user.GetName(), message) for _, u := range r.users { if u != user { result += u.Receive(message) + "\n" } } return result } // 使用示例 func main() { // 创建聊天室 chatRoom := NewConcreteChatRoom() // 创建用户 alice := NewChatUser("Alice") bob := NewChatUser("Bob") charlie := NewChatUser("Charlie") // 添加用户到聊天室 chatRoom.AddUser(alice) chatRoom.AddUser(bob) chatRoom.AddUser(charlie) // 发送消息 fmt.Println(alice.Send("Hello everyone!")) fmt.Println(bob.Send("Hi Alice!")) fmt.Println(charlie.Send("Hey guys!")) } ``` ## 适用场景 1. 对象间通信复杂 - 对象之间存在复杂的通信模式 - 需要集中管理对象间的交互 2. 对象耦合度高 - 对象之间直接引用过多 - 需要降低对象间的依赖关系 3. 系统扩展性要求高 - 需要频繁添加新的交互对象 - 需要灵活地改变对象间的通信方式 ## 优缺点 ### 优点 1. 减少耦合 - 将对象间的交互封装到中介者 - 对象之间不直接通信 2. 集中控制 - 集中管理对象间的交互 - 交互逻辑更容易维护 3. 提高复用性 - 对象可以独立变化 - 对象更容易复用 ### 缺点 1. 中介者可能过于复杂 - 承担了过多的职责 - 难以维护和扩展 2. 性能问题 - 所有通信都经过中介者 - 可能成为性能瓶颈 ## 实现要点 1. 中介者接口设计 - 定义通信协议 - 确定交互方式 2. 同事类设计 - 与中介者解耦 - 专注自身职责 3. 通信机制 - 消息传递方式 - 事件处理机制 ## 相关模式 1. 外观模式 - 简化系统接口 - 但不协调对象交互 2. 观察者模式 - 可用于实现中介者 - 处理对象间的通知 3. 命令模式 - 可与中介者结合 - 封装具体操作 ## 总结 中介者模式是一种用于处理对象之间复杂交互的行为型设计模式,它的核心价值在于: 1. 解耦 - 降低对象间的耦合度 - 简化对象间的关系 2. 维护性 - 集中管理交互逻辑 - 易于修改和扩展 3. 灵活性 - 对象可以独立变化 - 交互方式易于调整 在实际开发中,中介者模式常用于处理复杂的对象交互场景,如GUI组件通信、聊天室系统等。使用时需要注意避免中介者类过于庞大,合理划分职责,确保系统的可维护性。