您好,欢迎来到伴沃教育。
搜索
您的当前位置:首页C++设计模式:桥接模式

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

来源:伴沃教育

桥接模式

桥接模式(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 ]

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- bangwoyixia.com 版权所有 湘ICP备2023022004号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务