设计模式7:桥接模式
桥接模式是一种结构型设计模式,它把抽象化与实现化解耦,使得二者可以独立变化。
意图:将抽象部分与实现部分分离,使它们都可以独立的变化。
主要解决:在有多种可能会变化的情况下,用继承会造成类爆炸问题,扩展起来不灵活。
何时使用:实现系统可能有多个角度分类,每一种角度都可能变化。
如何解决:把这种多角度分类分离出来,让它们独立变化,减少它们之间耦合。
示例
我们以遥控器和电视设备为例,来说明桥接模式。
在这个例子中,我们可以把遥控器看作是抽象部分,而电视设备看作是实现部分。不同的遥控器和电视设备可以有不同的实现,但是它们之间的基本操作(如打开、关闭、切换频道等)是一样的。
首先,我们定义一个设备接口(电视设备):
type Device interface {
TurnOn()
TurnOff()
SetChannel(channel int)
}
然后,我们可以定义两种不同的设备,如电视和收音机:
type TV struct{}
func (tv *TV) TurnOn() {
fmt.Println("Turning on the TV")
}
func (tv *TV) TurnOff() {
fmt.Println("Turning off the TV")
}
func (tv *TV) SetChannel(channel int) {
fmt.Println("Setting channel on the TV to", channel)
}
type Radio struct{}
func (radio *Radio) TurnOn() {
fmt.Println("Turning on the Radio")
}
func (radio *Radio) TurnOff() {
fmt.Println("Turning off the Radio")
}
func (radio *Radio) SetChannel(channel int) {
fmt.Println("Setting channel on the Radio to", channel)
}
接着,我们定义一个遥控器接口:
type RemoteControl struct {
device Device
}
func (rc *RemoteControl) TurnOn() {
rc.device.TurnOn()
}
func (rc *RemoteControl) TurnOff() {
rc.device.TurnOff()
}
func (rc *RemoteControl) SetChannel(channel int) {
rc.device.SetChannel(channel)
}
最后,我们可以创建一个电视和一个遥控器,并通过遥控器来控制电视:
func main() {
tv := &TV{}
remote := &RemoteControl{device: tv}
remote.TurnOn()
remote.SetChannel(1)
remote.TurnOff()
}
这样,如果我们要添加新的设备或者新的遥控器,我们只需要分别实现设备接口和遥控器接口即可,而不需要修改现有的代码。这就是桥接模式的优点。