设计模式(五)| 青训营笔记

97 阅读2分钟

这篇文章主要讲设计模式中的桥接模式,也是七种结构型设计模式中的一种。

1. 桥接模式理念

桥接模式是一种结构型设计模式,它的主要设计思想是将抽象部分与它的实现部分分离,使它们都可以独立地变化。

2. 桥接模式设计思路

桥接模式的主要思路是将一个复杂的类层次结构拆分成多个简单的类层次结构。具体来说,桥接模式的实现步骤如下:

  • 定义抽象部分的接口(Abstraction)。
  • 定义实现部分的接口(Implementor)。
  • 在抽象部分中包含一个指向实现部分的引用(Implementor),并定义抽象方法(Operation)对外提供服务。
  • 在实现部分中实现实现部分接口,并提供具体方法对外提供服务。

3. 桥接模式应用场景

桥接模式通常适用于以下场景:

  • 当需要从多个维度来进行变化时,可以使用桥接模式来简化系统架构。
  • 当一个类存在两个或多个独立变化的维度时,可以使用桥接模式来进行解耦。
  • 当不希望在抽象部分和实现部分之间有固定的绑定关系时,可以使用桥接模式来进行解耦。

4. 桥接模式Golang代码举例

在Golang中,我们可以使用结构体和接口来实现桥接模式。以下是一个简单的代码示例:

package main

import "fmt"

type Implementor interface {
    Operation() string
}

type ConcreteImplementorA struct {}

func (c *ConcreteImplementorA) Operation() string {
    return "Operation A"
}

type ConcreteImplementorB struct {}

func (c *ConcreteImplementorB) Operation() string {
    return "Operation B"
}

type Abstraction interface {
    SetImplementor(Implementor)
    Operation() string
}

type ConcreteAbstraction struct {
    implementor Implementor
}

func (c *ConcreteAbstraction) SetImplementor(implementor Implementor) {
    c.implementor = implementor
}

func (c *ConcreteAbstraction) Operation() string {
    return c.implementor.Operation()
}

func main() {
    abstraction := &ConcreteAbstraction{}
    implementationA := &ConcreteImplementorA{}
    implementationB := &ConcreteImplementorB{}
    
    // 使用具体实现A
    abstraction.SetImplementor(implementationA)
    result := abstraction.Operation()
    fmt.Println(result)
    
    // 使用具体实现B
    abstraction.SetImplementor(implementationB)
    result = abstraction.Operation()
    fmt.Println(result)
}

在上述代码中,Implementor是实现部分的接口,ConcreteImplementorA和ConcreteImplementorB是实现部分的具体实现类。Abstraction是抽象部分的接口,ConcreteAbstraction是抽象部分的具体实现类。在ConcreteAbstraction中包含一个指向实现部分的引用,并定义了抽象方法Operation。在ConcreteImplementorA和ConcreteImplementorB中,均实现了实现部分的接口Implementor,并提供具体方法Operation对外提供服务。

在main函数中,我们先创建并初始化了ConcreteAbstraction对象,然后分别创建了ConcreteImplementorA和ConcreteImplementorB对象。最后,我们通过SetImplementor方法设置了具体的实现类,并通过Operation方法来调用具体的实现,最终打印输出结果:Operation A和Operation B。