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

总结

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

相关推荐
GISer_Jing8 小时前
AI Agent 人类参与HITL与知识检索RAG
人工智能·设计模式·aigc
Tiny_React13 小时前
Claude Code Skills 自优化架构设计
人工智能·设计模式
胖虎117 小时前
iOS中的设计模式(十)- 中介者模式(从播放器场景理解中介者模式)
设计模式·中介者模式·解耦·ios中的设计模式
Geoking.17 小时前
【设计模式】组合模式(Composite)详解
java·设计模式·组合模式
刀法孜然17 小时前
23种设计模式 3 行为型模式 之3.6 mediator 中介者模式
设计模式·中介者模式
Yu_Lijing18 小时前
基于C++的《Head First设计模式》笔记——单件模式
c++·笔记·设计模式
Geoking.18 小时前
【设计模式】外观模式(Facade)详解
java·设计模式·外观模式
点云SLAM18 小时前
C++设计模式之单例模式(Singleton)以及相关面试问题
c++·设计模式·面试·c++11·单例模式(singleton)
GISer_Jing1 天前
AI Agent 目标设定与异常处理
人工智能·设计模式·aigc
蔺太微1 天前
组合模式(Composite Pattern)
设计模式·组合模式