桥接模式通过接口与组合分离抽象与实现,如遥控器控制不同设备。定义Device接口,TV和Radio实现其方法;RemoteControl持有Device接口,实现基础操作;AdvancedRemote嵌入RemoteControl并扩展静音功能。使用时,tv := &TV{}; remote := NewRemoteControl(tv); remote.Power()输出"TV is ON";radio := &Radio{}; advanced := NewAdvancedRemote(radio); advanced.Mute()输出"Radio tuned to 0"和"Device muted"。新增设备或遥控器无需修改原有代码,符合开闭原则,Go的接口隐式实现与结构体组合使解耦更自然。

桥接模式用于将抽象部分与实现部分分离,使它们可以独立变化。在 Go 语言中,由于没有继承机制,通过接口和组合的方式天然适合实现桥接模式。这种结构特别适用于多维度变化的场景,比如不同类型的对象需要搭配不同的行为实现。
桥接的核心是把可变的部分提取为接口。假设我们有一组设备(如电视、收音机)和一组遥控器(基础遥控、高级遥控),设备控制方式可能不同,我们希望遥控器逻辑与设备解耦。
先定义设备控制的接口:
type Device interface {
TurnOn()
TurnOff()
SetChannel(channel int)
GetChannel() int
}这个接口代表“实现”层级,具体由各类设备实现。
立即学习“go语言免费学习笔记(深入)”;
以 TV 和 Radio 为例:
type TV struct {
channel int
}
<p>func (t *TV) TurnOn() {
fmt.Println("TV is ON")
}</p><p>func (t *TV) TurnOff() {
fmt.Println("TV is OFF")
}</p><p>func (t *TV) SetChannel(channel int) {
t.channel = channel
fmt.Printf("TV channel set to %d\n", channel)
}</p><p>func (t *TV) GetChannel() int {
return t.channel
}</p><p>type Radio struct {
channel int
}</p><p>func (r *Radio) TurnOn() {
fmt.Println("Radio is ON")
}</p><p>func (r *Radio) TurnOff() {
fmt.Println("Radio is OFF")
}</p><p>func (r *Radio) SetChannel(channel int) {
r.channel = channel
fmt.Printf("Radio tuned to %d\n", channel)
}</p><p>func (r *Radio) GetChannel() int {
return r.channel
}遥控器作为“抽象”部分,持有对 Device 的引用,不关心具体类型:
type RemoteControl struct {
device Device
}
<p>func NewRemoteControl(device Device) *RemoteControl {
return &RemoteControl{device: device}
}</p><p>func (r *RemoteControl) Power() {
r.device.TurnOn()
}</p><p>func (r *RemoteControl) Off() {
r.device.TurnOff()
}</p><p>func (r *RemoteControl) ChannelUp() {
channel := r.device.GetChannel()
r.device.SetChannel(channel + 1)
}</p><p>func (r *RemoteControl) ChannelDown() {
channel := r.device.GetChannel()
r.device.SetChannel(channel - 1)
}这样,RemoteControl 不依赖任何具体设备,只依赖 Device 接口。
如果需要更高级的遥控器,比如带静音按钮或屏幕显示,可以扩展抽象层:
type AdvancedRemote struct {
*RemoteControl
}
<p>func NewAdvancedRemote(device Device) *AdvancedRemote {
return &AdvancedRemote{RemoteControl: NewRemoteControl(device)}
}</p><p>func (a *AdvancedRemote) Mute() {
a.device.SetChannel(0)
fmt.Println("Device muted")
}AdvancedRemote 复用了基础遥控功能,并添加新行为,而无需修改设备实现。
使用示例:
tv := &TV{}
remote := NewRemoteControl(tv)
remote.Power() // TV is ON
remote.ChannelUp() // TV channel set to 1
<p>radio := &Radio{}
advanced := NewAdvancedRemote(radio)
advanced.Power() // Radio is ON
advanced.Mute() // Radio tuned to 0, Device muted通过桥接模式,设备类型和遥控器类型可以独立扩展。新增设备只需实现 Device 接口,新增遥控器只需组合已有逻辑并扩展。Go 的接口隐式实现和结构体组合让这种解耦自然且简洁。
基本上就这些。只要抓住“抽象与实现分离”的核心,用接口定义能力,用组合建立联系,就能有效解耦复杂结构。
以上就是Golang如何使用桥接模式解耦结构的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号