设计模式——桥接模式(bridge)

文章目录

引言

将抽象部分与它的实现部分分离,使它们都可以独立地变化。

在第一次看GoF的设计模式的书的时候,看到了他对bridge模式意图的描述如上,我顿感困惑,后面看架构图也依然非常疑惑,如下图:

对于这张图,你可以将Windowimp这右半边的内容理解为具体如何渲染 ,有多种不同的操作。而对于左半边可以理解为具体的窗口 ------展现什么形状和内容,以及使用什么渲染方式。

整一个桥接的做法其实就是使用抽象组合 代替具体组合 ,本来每个每一个渲染方式都需要和具体窗口组成一个类,而现在通过抽象组合 ,我们将类的编写数量从 O(n * m) 变成 O(n + m + 2) ,大大的减少了类的数量。这就是bridge模式的作用。

所以现在我再去回味GoF书中的那句话,我会觉得那是一个相对狭义的表述,其实无论是什么类似,只要场景合适都可以通过抽象组合(桥接)来减少类的数量。

代码实例

每一个形状都可以有不同的颜色,如果将它们死编码组合则会类数量爆炸,所以采用桥接

下面是示例代码,理解要点:

  • 智能指针的构造和转移
  • 抽象组合
  • 向上转型
cpp 复制代码
// 实现层次(Implementor)
class Color {
public:
    virtual std::string fill() const = 0;  // 返回颜色名称
    virtual ~Color() = default;
};

// 具体实现类(ConcreteImplementor)
class Red : public Color {
public:
    std::string fill() const override {
        return "Red";
    }
};

class Blue : public Color {
public:
    std::string fill() const override {
        return "Blue";
    }
};

// 抽象层次(Abstraction)
class Shape {
protected:
    std::shared_ptr<Color> color; // 桥接:组合一个实现层对象
public:
    explicit Shape(std::shared_ptr<Color> c) : color(std::move(c)) {}
    virtual void draw() const = 0;
    virtual ~Shape() = default;
};

// 扩充抽象层(RefinedAbstraction)
class Circle : public Shape {
public:
    using Shape::Shape;
    void draw() const override {
        std::cout << "Drawing a Circle in " << color->fill() << " color.\n";
    }
};

class Rectangle : public Shape {
public:
    using Shape::Shape;
    void draw() const override {
        std::cout << "Drawing a Rectangle in " << color->fill() << " color.\n";
    }
};

int main() {
    auto red = std::make_shared<Red>();
    auto blue = std::make_shared<Blue>();

    // 创建红色圆形和蓝色矩形
    Circle redCircle(red);
    Rectangle blueRectangle(blue);

    redCircle.draw();
    blueRectangle.draw();

    // 动态桥接:蓝色圆形
    Circle blueCircle(blue);
    blueCircle.draw();

    return 0;
}

总结

不必拘束于教科书的描述,依据具体场景找到最优方案来实现。

相关推荐
杨充1 天前
10.可测试性实战设计
设计模式·开源·代码规范
杨充1 天前
9.重构十二式的实战
设计模式·开源·代码规范
杨充1 天前
6.设计原则的全景图
设计模式·开源·全栈
杨充1 天前
2.面向对象的特性
设计模式
杨充1 天前
7.SOLID原则案例汇
设计模式·开源·全栈
杨充1 天前
8.反模式与坏味道
设计模式·开源·代码规范
杨充1 天前
3.接口vs抽象类比较
设计模式
咖啡八杯1 天前
文法、BNF与AST
java·设计模式·解释器模式·ast·文法
咖啡八杯2 天前
GoF设计模式——解释器模式
java·后端·spring·设计模式