桥接模式通过接口与组合分离抽象与实现,Go语言中以NotifySender接口定义发送方式,Notification结构体组合该接口实现多类型通知与多渠道发送的解耦,新增通知类型或发送方式无需修改原有代码,提升扩展性与维护性。

桥接模式的核心思想是将抽象部分与实现部分分离,使它们可以独立变化。在 Go 语言中,由于没有继承机制,桥接模式通过接口和组合的方式天然地得到了支持。这种方式让代码更具扩展性,尤其适合多维度变化的场景。
桥接模式的基本结构
桥接模式包含两个核心部分:
- 抽象层(Abstraction):定义高层控制逻辑,持有一个指向实现层的引用。
- 实现层(Implementor):提供底层操作接口,由具体类型实现。
两者通过组合连接,而不是继承,从而实现解耦。
实际应用场景:消息通知系统
假设我们要实现一个通知系统,支持多种消息类型(如普通通知、紧急通知),同时支持多种发送方式(如邮件、短信、钉钉)。如果用传统方式,每增加一种类型或渠道,都要新增类,导致类爆炸。使用桥接模式可有效解决这个问题。
立即学习“go语言免费学习笔记(深入)”;
定义实现接口:发送方式先定义一个发送器接口,表示不同的通知渠道:
type NotifySender interface {
Send(message string) error
}
再实现具体的发送方式:
type EmailSender struct{}
func (e *EmailSender) Send(message string) error {
fmt.Println("通过邮件发送:", message)
return nil
}
type SmsSender struct{}
func (s *SmsSender) Send(message string) error {
fmt.Println("通过短信发送:", message)
return nil
}
定义抽象:通知类型
通知类型持有发送器的引用,通过组合调用具体实现:
type Notification struct {
sender NotifySender
}
func NewNotification(sender NotifySender) *Notification {
return &Notification{sender: sender}
}
扩展不同类型的通知:
type NormalNotification struct {
*Notification
}
func NewNormalNotification(sender NotifySender) *NormalNotification {
return &NormalNotification{
Notification: NewNotification(sender),
}
}
func (n *NormalNotification) Notify(msg string) {
n.sender.Send("【普通】" + msg)
}
type UrgentNotification struct {
*Notification
}
func NewUrgentNotification(sender NotifySender) *UrgentNotification {
return &UrgentNotification{
Notification: NewNotification(sender),
}
}
func (u *UrgentNotification) Notify(msg string) {
u.sender.Send("【紧急】" + msg)
}
使用示例与灵活性体现
现在可以自由组合通知类型和发送方式:
func main() {
email := &EmailSender{}
sms := &SmsSender{}
normalEmail := NewNormalNotification(email)
urgentSms := NewUrgentNotification(sms)
normalEmail.Notify("系统即将维护")
urgentSms.Notify("服务器宕机!")
}
输出:
通过邮件发送: 【普通】系统即将维护
通过短信发送: 【紧急】服务器宕机!
如果需要新增“钉钉发送”,只需实现 NotifySender 接口;如果要加“定时通知”,只需扩展抽象部分。两者互不影响。
基本上就这些。Go 的接口和组合机制让桥接模式实现简洁自然,无需复杂设计,就能达到高内聚低耦合的效果。










