桥接模式(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 @ 2024-05-07 14:30  打工搬砖日记  阅读(4)  评论(0编辑  收藏  举报