十分钟学会一个设计模式---结构模式---桥接模式

50 阅读1分钟

一、作用

将类的功能层次结构和实现层次结构相分离,使二者能够独立地变化,并在两者之间搭建桥梁,实现桥接

二、与装饰器模式区别

装饰器是为了新增功能,桥接模式是将抽象和实现分离,两部分都可以扩展

三、 示例代码

class DrawApi {
public:
    virtual ~DrawApi() = default;
    virtual void Draw() = 0;
};

// 该实现部分可进行扩展
class RedCircle : public DrawApi {
public:
    void Draw() override {
        cout << "Red" << endl;
    }
};

class Shape {
public:
    virtual ~Shape() = default;
    explicit Shape(DrawApi* drawApi) {
        m_drawApi = drawApi;
    }
    virtual void Draw() = 0;

protected:
    // 该部分进行桥接
    DrawApi* m_drawApi;
};

// 该抽象可进行扩展
class Circle :public Shape {
public:
    void Draw() override{
        m_drawApi->Draw();
    }
    Circle(DrawApi* drawApi): Shape(drawApi){}
};

int main() {
    DrawApi* drawApi = new RedCircle;
    Shape* circle = new Circle(drawApi);
    circle->Draw();
}