设计模式之桥接模式

miloyang
0 评论
/ /
414 阅读
/
2755 字
20 2023-11

简介

桥接模式是一种结构型设计模式,用于将抽象部分和实现部分分离,使它们可以独立变化。桥接模式通过组合的方式,将抽象类和实现类分离,使得它们可以独立变化而不互相影响。

在桥接模式中,有两个关键角色

  • 抽象部分

    抽象部分定义了抽象类,并包含一个指向实现部分的引用,它通常包含抽象方法,其中的一些方法的实现委托给实现部分。

  • 实现部分

    实现部分是一个接口,定义了实现类的抽象方法,这些实现类负责实际执行抽象部分的方法。

jugelizi

比如我的车需要改造,改造的选项有修改颜色、修改轮毂、修改尾翼等等,我可以选择一项,也可以拼接,但是如果选择修改轮毂,必须要修改汽车颜色。

Demo

// ColorImplementor 颜色的实现接口
type ColorImplementor interface {
    Colorize() string
}

// ColorRed 具体的颜色实现类:红色
type ColorRed struct {
}

func (c ColorRed) Colorize() string {
    return "Red"
}

// ColorBlue 具体的颜色实现类:蓝色
type ColorBlue struct {
}

func (c ColorBlue) Colorize() string {
    return "Blue"
}

// Shape 形状的抽象类
type Shape interface {
    Hub() string                                      // 轮毂型号
    SetColorImplementor(implementor ColorImplementor) // 喷漆颜色
}

// Large 大号的轮毂
type Large struct {
    colorImplementor ColorImplementor
}

func (l *Large) Hub() string {
    return fmt.Sprintf("hub size large:8.0J,color:%s", l.colorImplementor.Colorize())
}
func (l *Large) SetColorImplementor(implementor ColorImplementor) {
    l.colorImplementor = implementor
}

// Medium 中号的轮毂
type Medium struct {
    colorImplementor ColorImplementor
}

func (m *Medium) Hub() string {
    return fmt.Sprintf("hub size medium:7.0J,color:%s", m.colorImplementor.Colorize())
}
func (m *Medium) SetColorImplementor(implementor ColorImplementor) {
    m.colorImplementor = implementor
}

测试:

func TestBridge(t *testing.T) {
    red := ColorRed{}
    large := Large{}
    large.SetColorImplementor(red)
    fmt.Println(large.Hub()) // hub size large:8.0J,color:Red

    blue := ColorBlue{}
    medium := Medium{}
    medium.SetColorImplementor(blue)
    fmt.Println(medium.Hub()) // hub size medium:7.0J,color:Blue
}

这个示例更好地体现了桥接模式的核心思想:将抽象部分和实现部分分离,使它们可以独立变化。在这个例子中,轮毂型号和颜色是两个不同的维度,桥接模式通过引入抽象类和实现接口,使得它们可以独立演化。

作用和场景

很明显,作用还是解耦,几乎所有的设计模式就是为了解耦。

  • 解耦抽象部分和实现部分

    桥接模式通过将抽象和实现分离,使得它们可以独立变化。这有助于减少系统中两个不断变化的维度之间的耦合,提高系统的灵活性。

  • 提高可扩展性

    桥接模式使得抽象和实现可以独立地扩展,而不影响彼此。新的抽象部分和新的实现部分可以方便地加入系统,而不需要修改现有的代码。

  • 多维度变化的系统

    当一个系统中有两个或多个维度的变化,并且这些维度需要独立地扩展时,可以考虑使用桥接模式。例如,图形绘制系统中的形状和颜色就是两个可能独立变化的维度。

  • 不希望使用继承或因继承导致的层次结构复杂

    桥接模式可以替代继承,避免使用多层次的继承结构,从而减少系统的复杂性。

  • 需要动态切换实现

    桥接模式允许客户端在运行时动态切换实现,这对于需要在运行时选择不同的实现策略的情况非常有用。

总体来说,桥接模式适用于那些有多个维度变化、需要灵活扩展、或者希望隐藏实现细节的情况。通过将抽象和实现分离,桥接模式有助于提高系统的灵活性和可扩展性。

人未眠
工作数十年
脚步未曾歇,学习未曾停
乍回首
路程虽丰富,知识未记录
   借此博客,与之共进步