StructuralC++verifiedVerified

Bridge Pattern in C++

Decouples an abstraction from its implementation so that the two can vary independently.

How to Implement the Bridge Pattern in C++

1Step 1: Define the Implementor interface

class Renderer {
public:
    virtual ~Renderer() = default;
    virtual void renderCircle(double x, double y, double r) = 0;
    virtual void renderRect(double x, double y, double w, double h) = 0;
};

2Step 2: Concrete implementors

class SVGRenderer : public Renderer {
public:
    void renderCircle(double x, double y, double r) override {
        std::cout << "<circle cx='" << x << "' cy='" << y << "' r='" << r << "'/>" << "\n";
    }
    void renderRect(double x, double y, double w, double h) override {
        std::cout << "<rect x='" << x << "' y='" << y << "' width='" << w << "' height='" << h << "'/>" << "\n";
    }
};

class CanvasRenderer : public Renderer {
public:
    void renderCircle(double x, double y, double r) override {
        std::cout << "ctx.arc(" << x << ", " << y << ", " << r << ")\n";
    }
    void renderRect(double x, double y, double w, double h) override {
        std::cout << "ctx.fillRect(" << x << ", " << y << ", " << w << ", " << h << ")\n";
    }
};

3Step 3: Abstraction that delegates to the implementor

class Shape {
protected:
    std::shared_ptr<Renderer> renderer_;
public:
    explicit Shape(std::shared_ptr<Renderer> renderer)
        : renderer_(std::move(renderer)) {}
    virtual ~Shape() = default;
    virtual void draw() = 0;
};

class CircleShape : public Shape {
    double x_, y_, r_;
public:
    CircleShape(double x, double y, double r, std::shared_ptr<Renderer> renderer)
        : Shape(std::move(renderer)), x_(x), y_(y), r_(r) {}
    void draw() override { renderer_->renderCircle(x_, y_, r_); }
};

int main() {
    auto svg = std::make_shared<SVGRenderer>();
    auto canvas = std::make_shared<CanvasRenderer>();

    CircleShape c1(10, 20, 5, svg);
    CircleShape c2(10, 20, 5, canvas);

    c1.draw();
    c2.draw();
}

Bridge Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Bridge Pattern in the Real World

A TV remote (abstraction) works with any brand of television (implementation) because both sides communicate through an agreed IR protocol (the bridge). Samsung and LG can redesign their TVs, and universal remote makers can add new button layouts—neither side needs to know about the other’s internal design, only the shared protocol.