C++设计模式:桥接模式

  • Post author:
  • Post category:其他


桥接模式

桥接模式(Bridge Pattern)是用于把抽象化与实现化解耦,使得二者可以独立变化。这种类型的设计模式属于结构型模式,它通过提供抽象化和实现化之间的桥接结构,来实现二者的解耦。

这种模式涉及到一个作为桥接的接口,使得实体类的功能独立于接口实现类。这两种类型的类可被结构化改变而互不影响。

使用场景

如果一个系统需要在构件的抽象化角色和具体化角色之间增加更多的灵活性,避免在两个层次之间建立静态的继承联系,通过桥接模式可以使它们在抽象层建立一个关联关系。

对于那些不希望使用继承或因为多层次继承导致系统类的个数急剧增加的系统,桥接模式尤为适用。

一个类存在两个独立变化的维度,且这两个维度都需要进行扩展。

优缺点

优点:

1、抽象和实现的分离。

2、优秀的扩展能力。

3、实现细节对客户透明。

缺点:

桥接模式的引入会增加系统的理解与设计难度,由于聚合关联关系建立在抽象层,要求开发者针对抽象进行设计与编程。

注意事项

对于两个独立变化的维度,使用桥接模式再适合不过了。

UML结构图

代码实现


first_interface.h


创建抽象类 – 绘制图形; 创建具体类 – 绘制红色圈圈、绘制绿色圈圈

#include <iostream>
using namespace std;

class DrawApi   //基类-绘制图形
{
public:
    DrawApi() {}
    virtual ~DrawApi() {}

    virtual void drawCircle(int radius, int x, int y) = 0;
};

class RedCircle: public DrawApi //子类-绘制红色圈圈
{
public:
    void drawCircle(int radius, int x, int y)
    {
        cout << "drawing circle [ color: red, radius: " << radius <<
                ", x: " << x << ", y: " << y << " ]" << endl;
    }
};

class GreenCircle: public DrawApi   //子类-绘制绿色圈圈
{
public:
    void drawCircle(int radius, int x, int y)
    {
        cout << "drawing circle [ color: green, radius: " << radius <<
                ", x: " << x << ", y: " << y << " ]" << endl;
    }
};


second_interface.h


把Shape 类DrawApi 类独立开,DrawApi 类作为接口在Shape 类中使用

可以实例化不同的DrawApi 对象来调用不同功能的drawCircle函数

#include "first_interface.h"

class Shape //基类-图形
{
public:
    virtual ~Shape() {}

    DrawApi * getDrawApi() { return this->drawApi; }
    virtual void draw() = 0;

protected:
    DrawApi *drawApi;

    Shape(DrawApi *drawApi): drawApi(drawApi) {}
};

class Circle: public Shape  //子类-圆形
{
public:
    Circle(int radius, int x, int y, DrawApi *drawApi): Shape(drawApi)
    {
        this->x = x;
        this->y = y;
        this->radius = radius;
    }

    void draw()
    {
        getDrawApi()->drawCircle(radius, x, y);
    }

private:
    int x;
    int y;
    int radius;
};


main.cpp


实例应用 – 使用 Shape 和 DrawAPI 类画出不同颜色的圆

#include "second_interface.h"

int main()
{
    DrawApi *redDrawApi = new RedCircle();
    DrawApi *greenDrawApi = new GreenCircle();

    Shape *redCircle = new Circle(100, 10, 10, redDrawApi);
    Shape *greenCircle = new Circle(100, 10, 10, greenDrawApi);

    redCircle->draw();
    greenCircle->draw();

    return 0;
}

运行结果:
drawing circle [ color: red, radius: 100, x: 10, y: 10 ]
drawing circle [ color: green, radius: 100, x: 10, y: 10 ]




本文福利,








费领取Qt开发学习资料包、技术视频,内容包括(C++语言基础,Qt编程入门,QT信号与槽机制,QT界面开发-图像绘制,QT网络,QT数据库编程,QT项目实战,QSS,OpenCV,Quick模块,面试题等等)↓↓↓↓↓↓见下面↓↓文章底部点击





费领取↓↓





版权声明:本文为m0_73443478原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。