C++设计模式(十八):桥接模式

桥接模式

桥接模式用于将抽象部分与实现部分分离,使得它们可以独立地变化。
桥接模式避免了使用继承导致的类爆炸问题,提供更灵活的扩展方式。

在这里插入图片描述

#include <bits/stdc++.h>

using namespace std;

// 抽象接口 DrawAPI
class DrawAPI
{
public:
    virtual ~DrawAPI() = default;
    virtual void drawCircle(int radius, int x, int y) = 0; // 绘制圆的方法
};

// 具体实现类 RedCircle
class RedCircle : public DrawAPI
{
public:
    void drawCircle(int radius, int x, int y) override
    {
        cout << "Drawing Circle[ Color: Red, Radius: " << radius
             << ", X: " << x << ", Y: " << y << "]" << endl;
    }
};

// 具体实现类 GreenCircle
class GreenCircle : public DrawAPI
{
public:
    void drawCircle(int radius, int x, int y) override
    {
        cout << "Drawing Circle[ Color: Green, Radius: " << radius
             << ", X: " << x << ", Y: " << y << "]" << endl;
    }
};

// 抽象类 Shape
class Shape
{
protected:
    unique_ptr<DrawAPI> drawAPI; // 持有一个实现抽象

public:
    Shape(unique_ptr<DrawAPI> drawAPI) : drawAPI(move(drawAPI)) {} // 修正构造函数
    virtual ~Shape() = default;
    virtual void draw() = 0; // 绘制方法的抽象
};

// 具体类 Circle
class Circle : public Shape
{
private:
    int x, y, radius;

public:
    Circle(int x, int y, int radius, unique_ptr<DrawAPI> drawAPI)
        : Shape(move(drawAPI)), x(x), y(y), radius(radius) {} // 修正构造函数

    void draw() override
    {
        drawAPI->drawCircle(radius, x, y); // 委托实现类绘制
    }
};

// 桥接模式演示类
class BridgePatternDemo
{
public:
    void main()
    {
        unique_ptr<Shape> redCircle = make_unique<Circle>(100, 100, 10, make_unique<RedCircle>());
        unique_ptr<Shape> greenCircle = make_unique<Circle>(100, 100, 10, make_unique<GreenCircle>());

        redCircle->draw();   // 绘制红色圆
        greenCircle->draw(); // 绘制绿色圆
    }
};

// 主函数
int main()
{
    BridgePatternDemo demo;
    demo.main(); // 执行演示
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值