Bridge Pattern

Bridge Pattern

The intent is to separate the abstraction from the implementation so that both can evolve independently.

UML

https://www.runoob.com/design-pattern/bridge-pattern.html

Used in Qt:

abstraction

class QPaintDevice{
public:
virtual QPaintEngine * paintEngine() const = 0;
``````
}

implementation

class QPaintEngine{
public:
``````
}

Client Code:

class QPainter{
public:
```````
}

Some Codes:

1. Define the Implementor (Interface for implementation)

#include <iostream>
#include <memory>

// Implementor interface
class DrawingAPI {
public:
    virtual ~DrawingAPI() = default;
    virtual void drawCircle(double x, double y, double radius) = 0;
};

// Concrete Implementor 1
class DrawingAPI1 : public DrawingAPI {
public:
    void drawCircle(double x, double y, double radius) override {
        std::cout << "Drawing Circle with API1 at (" << x << ", " << y << ") with radius " << radius << std::endl;
    }
};
2. Create Concrete Implementors
// Concrete Implementor 2
class DrawingAPI2 : public DrawingAPI {
public:
    void drawCircle(double x, double y, double radius) override {
        std::cout << "Drawing Circle with API2 at (" << x << ", " << y << ") with radius " << radius << std::endl;
    }
};

3. Define the Abstraction

// Abstraction
class Shape {
public:
    virtual ~Shape() = default;
    virtual void draw() = 0;
    virtual void resize(double factor) = 0;
};

4. Refine the Abstraction (Extend the Abstraction)

// Refined Abstraction
class CircleShape : public Shape {
private:
    std::shared_ptr<DrawingAPI> drawingAPI;
    double x, y, radius;

public:
    CircleShape(std::shared_ptr<DrawingAPI> api, double x, double y, double radius)
        : drawingAPI(std::move(api)), x(x), y(y), radius(radius) {}

    void draw() override {
        drawingAPI->drawCircle(x, y, radius);  // Delegate the drawing task to the DrawingAPI
    }

    void resize(double factor) override {
        radius *= factor;  // Resize the circle by a factor
    }
};

5. Client Code

int main() {
    // Create a circle using DrawingAPI1
    std::shared_ptr<DrawingAPI> api1 = std::make_shared<DrawingAPI1>();
    std::shared_ptr<Shape> circle1 = std::make_shared<CircleShape>(api1, 1.0, 2.0, 3.0);

    // Create a circle using DrawingAPI2
    std::shared_ptr<DrawingAPI> api2 = std::make_shared<DrawingAPI2>();
    std::shared_ptr<Shape> circle2 = std::make_shared<CircleShape>(api2, 4.0, 5.0, 6.0);

    // Draw the circles
    circle1->draw();
    circle2->draw();

    // Resize the circles
    circle1->resize(2.0);
    circle2->resize(0.5);

    // Draw the circles again after resizing
    circle1->draw();
    circle2->draw();

    return 0;
}
相关推荐
Jack_hrx5 个月前
Java 设计模式之桥接模式(Bridge Pattern)
java·设计模式·桥接模式·bridge pattern
西西弗Sisyphus5 个月前
C++ 桥接模式 (Bridge Pattern)
c++·桥接模式·bridge pattern
#!-bin-bash10 个月前
内核无法转发交换机trunk-udp-分片数据包
网络·网络协议·udp·系统安全·bridge pattern