桥接模式通过接口与组合将抽象与实现分离,使设备与遥控器可独立扩展。定义Device接口并实现TV等具体设备,遥控器通过持有Device接口实现解耦,基础遥控器RemoteControl提供通用控制,高级遥控器AdvancedRemoteControl通过组合扩展功能,新增设备或遥控类型无需大量继承,结构清晰且易于维护。

桥接模式的核心是将抽象部分与实现部分分离,使它们可以独立变化。在Golang中,虽然没有类和继承的概念,但通过接口和组合,可以非常自然地实现桥接模式。这种模式特别适合在多个维度扩展功能时使用,比如不同类型的对象需要搭配不同的实现方式,避免类的爆炸式增长。
假设我们有一系列电子设备(如电视、收音机),每种设备都可以通过不同的遥控器(基础遥控、高级遥控)来控制。如果直接用继承来实现,每增加一个设备或遥控类型,就需要新增大量组合类。使用桥接模式,我们可以将“设备控制”这一行为抽象出来,与具体设备解耦。
定义设备接口:
type Device interface {
TurnOn()
TurnOff()
SetChannel(channel int)
}
实现具体的设备,比如电视:
立即学习“go语言免费学习笔记(深入)”;
type TV struct {
channel int
}
<p>func (t *TV) TurnOn() {
fmt.Println("TV is turning on...")
}</p><p>func (t *TV) TurnOff() {
fmt.Println("TV is turning off...")
}</p><p>func (t *TV) SetChannel(channel int) {
t.channel = channel
fmt.Printf("TV switched to channel %d\n", channel)
}
遥控器作为抽象部分,持有对设备的引用,将操作委托给具体设备实现:
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) ChannelUp() {
r.device.SetChannel(r.device.GetChannel() + 1)
}</p><p>func (r *RemoteControl) ChannelDown() {
r.device.SetChannel(r.device.GetChannel() - 1)
}
注意:上面代码中 GetChannel() 尚未在 Device 接口中定义。为了支持频道切换,需要补充该方法:
type Device interface {
TurnOn()
TurnOff()
SetChannel(channel int)
GetChannel() int
}
为 TV 补充 GetChannel 方法:
func (t *TV) GetChannel() int {
return t.channel
}
可以在不修改设备的前提下,扩展遥控器功能。比如增加静音按钮或一键换台:
type AdvancedRemoteControl struct {
RemoteControl
}
<p>func NewAdvancedRemoteControl(device Device) *AdvancedRemoteControl {
return &AdvancedRemoteControl{
RemoteControl: RemoteControl{device: device},
}
}</p><p>func (a *AdvancedRemoteControl) Mute() {
fmt.Println("TV is muted.")
}
这样,AdvancedRemoteControl 复用了基础遥控器的行为,并添加了新功能,而所有设备实现不受影响。
在 main 函数中组合使用:
func main() {
tv := &TV{}
remote := NewRemoteControl(tv)
advancedRemote := NewAdvancedRemoteControl(tv)
<pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">remote.Power() // TV is turning on...
remote.ChannelUp() // TV switched to channel 1
advancedRemote.Mute() // TV is muted.}
如果之后加入收音机或其他设备,只需实现 Device 接口,即可无缝接入所有遥控器。
桥接模式让抽象(遥控器)和实现(设备)各自独立演化。Golang通过接口定义行为,通过结构体组合实现复用,天然支持这种设计。关键是把“变化的两个维度”分开:一个是设备类型,一个是控制方式。两者通过接口连接,而不是继承绑定。
基本上就这些。结构清晰,扩展灵活,是处理多维度变化的实用方案。
以上就是Golang桥接模式应用 抽象与实现解耦的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号