如何在Golang中实现中介者模式_Golang中介者模式实现方法汇总

中介者模式通过封装对象交互降低耦合,go中常用接口结构体组合实现;示例包含基础同步通信、基于channel异步中介及泛型事件总线,适用于Gui游戏开发与微服务协调。

如何在Golang中实现中介者模式_Golang中介者模式实现方法汇总

Go语言中实现中介者模式,核心是通过一个中介者对象来封装一系列对象之间的交互,避免对象之间直接引用,降低耦合度。以下是几种常见的golang中介者模式实现方法,适用于不同场景。

1. 基础结构体与接口实现

定义中介者接口和同事接口,通过结构体组合实现解耦通信。

示例代码:

先定义两个接口:

Mediator 接口:负责处理同事之间的消息转发。

立即学习go语言免费学习笔记(深入)”;

Colleague 接口:表示参与交互的对象,持有中介者引用。

实现方式如下:

type Mediator interface {     Send(message string, sender Colleague) } <p>type Colleague interface { Receive(message string) }</p><p>type ConcreteMediator struct { ColleagueA <em>UserA ColleagueB </em>UserB }</p><p>func (m *ConcreteMediator) Send(message string, sender Colleague) { if sender == m.ColleagueA { m.ColleagueB.Receive(message) } else { m.ColleagueA.Receive(message) } }</p><p>type UserA struct { mediator Mediator }</p><p>func (u *UserA) Send(msg string) { u.mediator.Send(msg, u) }</p><p>func (u *UserA) Receive(msg string) { println("UserA received:", msg) }</p><p>// UserB 实现类似 UserA type UserB struct { mediator Mediator }</p><p>func (u *UserB) Send(msg string) { u.mediator.Send(msg, u) }</p><p>func (u *UserB) Receive(msg string) { println("UserB received:", msg) } 

使用方式:

mediator := &ConcreteMediator{} a := &UserA{mediator: mediator} b := &UserB{mediator: mediator} mediator.ColleagueA = a mediator.ColleagueB = b <p>a.Send("Hello from A") // 输出:UserB received: Hello from A b.Send("Hi from B")    // 输出:UserA received: Hi from B 

2. 使用通道(Channel)实现异步中介者

并发场景下,可用 channel 作为消息队列,由中介者统一调度,实现松耦合、异步通信。

如何在Golang中实现中介者模式_Golang中介者模式实现方法汇总

百度文心百中

百度大模型语义搜索体验中心

如何在Golang中实现中介者模式_Golang中介者模式实现方法汇总 22

查看详情 如何在Golang中实现中介者模式_Golang中介者模式实现方法汇总

适合多个组件间事件通知、状态广播等场景。

实现思路:

  • 定义消息结构体,包含内容和发送者标识
  • 中介者监听 channel,根据类型转发消息
  • 各同事通过 channel 发送消息给中介者

示例片段:

type Message struct {     Content string     From    string } <p>type AsyncMediator struct { messages chan Message }</p><p>func NewAsyncMediator() *AsyncMediator { m := &AsyncMediator{messages: make(chan Message, 10)} go m.Start() return m }</p><p>func (m *AsyncMediator) Start() { for msg := range m.messages { if msg.From == "A" { println("Forwarding to B:", msg.Content) // 模拟发给 B } else { println("Forwarding to A:", msg.Content) } } }</p><p>func (m *AsyncMediator) Send(msg Message) { m.messages <- msg } 

3. 泛型增强的中介者(Go 1.18+)

利用泛型可以让中介者支持不同类型的消息或同事,提升复用性。

例如定义一个通用事件总线:

type EventHandler[T any] func(T) <p>type EventBus struct { handlers map[string][]interface{} }</p><p>func (e *EventBus) Subscribe[T any](event string, handler EventHandler[T]) { // 订阅逻辑 }</p><p>func (e *EventBus) Publish(event string, data interface{}) { // 触发对应事件 } 

这种模式更接近“发布-订阅”,但可视为中介者的一种扩展形式,尤其适合复杂系统中的模块通信。

4. 实际应用场景建议

中介者模式常用于以下场景:

  • GUI组件通信:按钮、输入框、状态栏之间的联动
  • 游戏开发:角色、UI、音效系统间的协调
  • 微服务中间层:统一处理服务间调用逻辑

在Go中,由于没有继承机制,更多依赖组合与接口,因此中介者通常以结构体字段方式注入同事对象,保持轻量。

基本上就这些。根据项目复杂度选择合适实现方式,简单场景用接口+结构体即可,高并发考虑 channel,大型系统可结合依赖注入优化管理。

上一篇
下一篇
text=ZqhQzanResources