The Bridge pattern, also known as the Interface or Handle/Body pattern, decouples an abstraction from its implementation so that both can vary independently. It is a structural design pattern that favors composition over inheritance, offering a more flexible and maintainable approach compared to multiple inheritance.
Core Components of the Bridge Pattern
- Abstraction: Maintains a reference to the implementation and defines the high-level interface.
- RefinedAbstraction: Extends the abstraction interface and modifies or enhances its behavior.
- Implementor: Declares the low-level operations that the abstraction uses. Usually an interface or abstract class.
- ConcreteImplementor: Implements the actual behavior defined by the Implementor interface.
Implementation Example
Below is a typical implementation of the Bridge pattern in Java with modifeid structure and naming conventions to preserve the logic while reducing similarity.
Define the Implemantation Interface
public interface Backend {
void execute();
}
Implement Concrete Backend A
public class BackendA implements Backend {
public void execute() {
System.out.println("Executing with Backend A");
}
}
Create the Abstraction Base Class
public abstract class Service {
protected Backend backend;
public Service(Backend backend) {
this.backend = backend;
}
public abstract void run();
}
Refine the Abstraction
public class ExtendedService extends Service {
public ExtendedService(Backend backend) {
super(backend);
}
public void run() {
backend.execute();
System.out.println("Enhanced service logic applied");
}
}
Use Cases
The Bridge pattern is particularly useful when:
- A class has multiple dimensions that evolve independently.
- You want to avoid a combinatorial explosion of subclasses through inheritance.
- You need a more flexible and loosely coupled alternative to multiple inheritance.
Advantages and Limitations
Advantages:
- Promotes separation of concerns between abstraction and implementation.
- Improves system scalability and extensibility.
- Aligns with SOLID principles—especially the Open/Closed and Composition over Inheritance principles.
Limitations:
- Increases complexity by introducing additional abstraction layers.
- Requires a clear understanding of both abstraction and implementation hierarchies.
Real-World Application
The Bridge pattern is widely used in frameworks and APIs. For example, in the JDBC API, the driver implementation is decoupled from the connection interface, allowing different database vendors to plug in their implementations without altering the client code.