Sobes.tech
Middle+

Tell us about the Bridge pattern — what is it for and how does it work?

sobes.tech AI

Answer from AI

The Bridge pattern is used to separate an abstraction from its implementation so that they can vary independently. This is useful when you want to avoid tight coupling between the interface and implementation, especially if both parts can have different variations.

How it works:

  • There is an abstraction (for example, an interface or an abstract class) that contains a reference to an implementation object.
  • The implementation is a separate interface or class that encapsulates specific details.
  • The abstraction delegates calls to the implementation.

Example in Java:

// Implementation
interface Renderer {
    void renderCircle(float radius);
}

class VectorRenderer implements Renderer {
    public void renderCircle(float radius) {
        System.out.println("Drawing a circle of radius " + radius + " as lines");
    }
}

class RasterRenderer implements Renderer {
    public void renderCircle(float radius) {
        System.out.println("Drawing pixels for circle of radius " + radius);
    }
}

// Abstraction
abstract class Shape {
    protected Renderer renderer;
    public Shape(Renderer renderer) {
        this.renderer = renderer;
    }
    public abstract void draw();
}

class Circle extends Shape {
    private float radius;
    public Circle(Renderer renderer, float radius) {
        super(renderer);
        this.radius = radius;
    }
    public void draw() {
        renderer.renderCircle(radius);
    }
}

// Usage
Renderer vector = new VectorRenderer();
Shape circle = new Circle(vector, 5);
circle.draw();

Thus, you can change the implementation of Renderer independently of the shape classes, and vice versa.