Overview
The Bridge Design Pattern is used to decouple an abstraction from its implementation, allowing them to vary independently. It is often employed when an abstraction can have multiple implementations.
Key Characteristics
- Separates abstraction and implementation into two distinct hierarchies.
- Enables the abstraction and implementation to evolve independently.
- Promotes flexibility and scalability in the codebase.
Implementation
The following is an example of a Bridge implementation in Java:
// Implementor interface
interface DrawAPI {
void drawCircle(int radius, int x, int y);
}
// Concrete Implementors
class RedCircle implements DrawAPI {
@Override
public void drawCircle(int radius, int x, int y) {
System.out.println("Drawing Circle[ color: red, radius: " + radius + ", x: " + x + ", y: " + y + "]");
}
}
class GreenCircle implements DrawAPI {
@Override
public void drawCircle(int radius, int x, int y) {
System.out.println("Drawing Circle[ color: green, radius: " + radius + ", x: " + x + ", y: " + y + "]");
}
}
// Abstraction
abstract class Shape {
protected DrawAPI drawAPI;
protected Shape(DrawAPI drawAPI) {
this.drawAPI = drawAPI;
}
public abstract void draw();
}
// Refined Abstraction
class Circle extends Shape {
private int x, y, radius;
public Circle(int x, int y, int radius, DrawAPI drawAPI) {
super(drawAPI);
this.x = x;
this.y = y;
this.radius = radius;
}
@Override
public void draw() {
drawAPI.drawCircle(radius, x, y);
}
}
// Demo
public class BridgeDemo {
public static void main(String[] args) {
Shape redCircle = new Circle(100, 100, 10, new RedCircle());
Shape greenCircle = new Circle(200, 200, 20, new GreenCircle());
redCircle.draw();
greenCircle.draw();
}
}
When to Use
- When you want to decouple abstraction and implementation so they can evolve independently.
- When you need to combine different abstractions and implementations dynamically.
Advantages
- Encourages separation of concerns by decoupling abstraction and implementation.
- Improves flexibility and scalability.
Disadvantages
- Can add complexity due to the need for multiple hierarchies.