如何在Golang中实现桥接模式解耦模块_Golang桥接模式设计技巧

桥接模式在Go中通过组合+接口抽象解耦抽象与实现,适用于消息类型×通知渠道等双变化维度场景;定义Notifier接口封装发送行为,AlertService通过字段组合持有该接口并动态切换具体实现。

桥接模式在 Go 中不是靠继承,而是靠组合 + 接口抽象来解耦“抽象”与“实现”。它适合当系统有两个变化维度(比如:消息类型 × 通知渠道),且你希望它们能独立扩展、互不影响时使用。

用接口定义“实现层”

把易变的具体行为(如发送短信、邮件、站内信)抽成接口,让具体实现各自负责细节:

// 实现层接口:通知方式
type Notifier interface {
  Send(content string) error
}

type SMSNotifier struct{}
func (s SMSNotifier) Send(content string) error {
  fmt.Println("发送短信:", content)
  return nil
}

type EmailNotifier struct{}
func (e EmailNotifier) Send(content string) error {
  fmt.Println("发送邮件:", content)
  return nil
}

用结构体持有接口,封装“抽象层”

抽象层(比如告警服务、营销推送)不关心怎么发,只依赖 Notifier 接口。它通过字段组合持有实现,并在方法中调用:

// 抽象层:业务逻辑
type AlertService struct {
  notifier Notifier // 桥接点:依赖接口,不绑定具体实现
}

func NewAlertService(n Notifier) *AlertService {
  return &AlertService{notifier: n}
}

func (a *AlertService) Trigger(message string) {
  a.notifier.Send("[ALERT] " + message)
}

运行时动态切换实现,零修改扩展

同一份 AlertService 代码,可自由搭配不同 Notifier,无需改结构或方法:

func main() {
  // 短信告警
  sms := NewAlertService(SMSNotifier{})
  sms.Trigger("CPU 使用率超 90%")
  
  // 邮件告警(只需换 notifier,其余不变)
  email := NewAlertService(EmailNotifier{})
  email.Trigger("数据库连接池耗尽")
}

进阶技巧:支持配置化与多级桥接

实际项目中可进一步增强灵活性:

  • 用工厂函数根据配置字符串返回对应 Notifier(如 "sms" → SMSNotifier)
  • Notifier 接口可增加 Context、Options 等参数,适配真实场景(超时、重试、模板)
  • 若还需区分“消息类型”(文本/富媒体)和“渠道”,可再加一层 MessageBuilder 接口,形成双桥接

基本上就这些。Go 的桥接不靠虚函数表,而靠接口的隐式实现和结构体的轻量组合——简洁,够用,也容易测试。