TechnologyZer
technologyzer.com

Bridge Design Pattern

Bridge design pattern is a structural pattern that decouples an abstraction from its implementation, allowing both to vary independently. It’s like building a bridge between two layers of abstraction, enabling them to evolve separately without being tightly coupled.

Key components of the Bridge pattern include:

  1. Abstraction: Defines the interface or abstract class that clients interact with. It contains a reference to the implementation interface.
  2. Implementor: Defines the interface for concrete implementations. It is decoupled from the abstraction and can evolve independently.
  3. Refined Abstraction: Extends the abstraction by providing additional functionality or customization.
  4. Concrete Implementor: Implements the interface defined by the implementor.
  5. Concrete Abstraction: Implements the abstraction interface and delegates to the implementor.

~:Sample code of Bridge Design Pattern:~

// Abstraction
interface Shape {
    void draw();
}

// Implementor
interface Color {
    void applyColor();
}

// Refined Abstraction
abstract class AbstractShape implements Shape {
    protected Color color;

    public AbstractShape(Color color) {
        this.color = color;
    }
}

// Concrete Implementors
class RedColor implements Color {
    @Override
    public void applyColor() {
        System.out.println("Applying red color");
    }
}
class BlueColor implements Color {
    @Override
    public void applyColor() {
        System.out.println("Applying blue color");
    }
}

// Concrete Abstraction
class Circle extends AbstractShape {
    public Circle(Color color) {
        super(color);
    }

    @Override
    public void draw() {
        System.out.print("Drawing Circle: ");
        color.applyColor();
    }
}

class Square extends AbstractShape {
    public Square(Color color) {
        super(color);
    }

    @Override
    public void draw() {
        System.out.print("Drawing Square: ");
        color.applyColor();
    }
}

// Client code
public class Main {
    public static void main(String[] args) {
        // Create shapes with different colors
        Shape redCircle = new Circle(new RedColor());
        Shape blueSquare = new Square(new BlueColor());

        // Draw shapes
        redCircle.draw();
        blueSquare.draw();
    }
}

Leave a Comment