设计模式——桥接模式(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;
}

总结

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

相关推荐
进击的小头3 小时前
设计模式组合应用:传感器数据采集与处理系统
c语言·设计模式
茶本无香4 小时前
设计模式之十一—桥接模式:解耦抽象与实现的艺术
设计模式·桥接模式
短剑重铸之日4 小时前
《设计模式》第四篇:观察者模式
java·后端·观察者模式·设计模式
七夜zippoe6 小时前
API网关设计模式实战 Spring Cloud Gateway路由过滤限流深度解析
java·设计模式·gateway·路由·api网关
yangpipi-21 小时前
2. 设计模式之结构型模式
设计模式
进击的小头1 天前
设计模式组合应用:嵌入式通信协议栈
c语言·设计模式·策略模式
致Great1 天前
智能体的设计模式探讨
设计模式
BD_Marathon1 天前
设计模式——单一职责原则
设计模式·单一职责原则
stevenzqzq1 天前
Slot API 设计模式
设计模式·compose
reddingtons1 天前
Cascadeur:动态总是“飘”?“物理外挂流” 3分钟直出重力感 2D 立绘
游戏·设计模式·aigc·设计师·游戏策划·游戏美术·cascadeur