Sobes.tech
Middle — Middle+

Explain the concept and application of the 'bridge' design pattern in software development.

sobes.tech AI

Answer from AI

The Bridge design pattern is used to separate an abstraction from its implementation so that they can vary independently.

The idea is that we have two class hierarchies: one for the abstraction (interface), and another for the implementation. The abstraction contains a reference to an implementation object and delegates work to it. This allows changing the implementation without modifying the abstraction and vice versa.

Applications:

  • When you need to avoid tight coupling between abstraction and implementation.
  • When both parts can evolve independently.
  • To support multiple implementation options that can be combined with different abstractions.

Example in Java:

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

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

class RasterRenderer implements Renderer {
    public void renderCircle(float x, float y, float radius) {
        System.out.println("Drawing pixels for circle at (" + x + "," + y + ") with 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 x, y, radius;
    public Circle(Renderer renderer, float x, float y, float radius) {
        super(renderer);
        this.x = x; this.y = y; this.radius = radius;
    }
    public void draw() {
        renderer.renderCircle(x, y, radius);
    }
}

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

This way, you can change the rendering method (VectorRenderer or RasterRenderer) without changing the Circle class.

Explain the concept and application of the 'bridge'… - sobes.tech