DEV Community

eidher
eidher

Posted on • Edited on

1 1

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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay