设计模式7 - 桥接模式

作者:billy
版权声明:著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处

桥接模式

桥接模式(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 ]
  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值