DEV Community

eidher
eidher

Posted on • Updated on

Bridge Pattern

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

Alt Text

Participants

  • Abstraction: defines the abstraction's interface. Maintains a reference to an object of type Implementor.
  • RefinedAbstraction: extends the interface defined by Abstraction.
  • Implementor: defines the interface for implementation classes. This interface doesn't have to correspond exactly to Abstraction's interface; in fact, the two interfaces can be quite different. Typically the Implementation interface provides only primitive operations, and Abstraction defines higher-level operations based on these primitives.
  • ConcreteImplementor: implements the Implementor interface and defines its concrete implementation.

Code

public class Main {

    public static void main(String[] args) {
        Abstraction ab = new RefinedAbstraction();
        ab.implementor = new ConcreteImplementorA();
        ab.operation();
        ab.implementor = new ConcreteImplementorB();
        ab.operation();
    }
}

public class Abstraction {

    protected Implementor implementor;

    public void setImplementor(Implementor implementor) {
        this.implementor = implementor;
    }

    public void operation() {
        implementor.operation();
    }
}

public interface Implementor {

    public void operation();
}

public class RefinedAbstraction extends Abstraction {

    @Override
    public void operation() {
        implementor.operation();
    }
}

public class ConcreteImplementorA implements Implementor {

    @Override
    public void operation() {
        System.out.println("ConcreteImplementorA Operation");
    }
}

public class ConcreteImplementorB implements Implementor {

    @Override
    public void operation() {
        System.out.println("ConcreteImplementorB Operation");
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

ConcreteImplementorA Operation
ConcreteImplementorB Operation
Enter fullscreen mode Exit fullscreen mode

Top comments (0)