Bridge
Definition
Decouple an abstraction from its implementation so that the two can vary independently.
UML class diagram
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.
- ConcreteImplementor
- implements the Implementor interface and defines its concrete implementation.
Sample code in Java
package com.hong.bridge; interface Implementor { public void operation(); } class ConcreteImplementorA implements Implementor { @Override public void operation() { System.out.println("Calls Implementor's operation from ConcreteImplementorA"); } } class ConcreteImplementorB implements Implementor { @Override public void operation() { System.out.println("Calls Implementor's operation from ConcreteImplementorB"); } } interface Abstraction { public void setImplementor(Implementor implementor); public void operation(); } class RefinedAbstraction implements Abstraction { private Implementor implementor; public RefinedAbstraction(){} @Override public void setImplementor(Implementor implementor) { this.implementor = implementor; } @Override public void operation() { if(null != implementor) implementor.operation(); } } public class Bridge_structure { public static void main(String[] args) { Abstraction rf_abs = new RefinedAbstraction(); rf_abs.setImplementor(new ConcreteImplementorA()); rf_abs.operation(); rf_abs.setImplementor(new ConcreteImplementorB()); rf_abs.operation(); } }