桥接模式(C++)

桥接模式:主要应用于需求复杂,不确定的场景,用于解耦

#include <iostream>
using namespace std;
// Implementor
class DrawAPI
{
public:
virtual void drawCircle(int radius, int x, int y) = 0;
virtual ~DrawAPI() {}
};
// ConcreteImplementorA
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;
}
};
// ConcreteImplementorB
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;
}
};
// Abstraction
class Shape
{
protected:
DrawAPI *drawAPI;
Shape(DrawAPI *drawAPI) : drawAPI(drawAPI) {}
public:
virtual void draw() = 0;
virtual ~Shape() {}
};
// RefinedAbstraction
class Circle : public Shape
{
private:
int x, y, radius;
public:
Circle(int x, int y, int radius, DrawAPI *drawAPI) : Shape(drawAPI), x(x), y(y), radius(radius) {}
void draw() override
{
drawAPI->drawCircle(radius, x, y);
}
};
// Client code
int main()
{
Shape *redCircle = new Circle(100, 100, 10, new RedCircle());
Shape *greenCircle = new Circle(100, 100, 10, new GreenCircle());
redCircle->draw();
greenCircle->draw();
delete redCircle;
delete greenCircle;
return 0;
}

在这个例子中,DrawAPI 是实现类接口,RedCircle 和 GreenCircle 是具体的实现类。Shape 是抽象类,而 Circle 是扩展抽象类。通过这种方式,Circle 类的实现可以独立于画圆的颜色,从而实现了代码的解耦

posted @   打工搬砖日记  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示