Bridge Pattern
Introduction
The Bridge Pattern is a structural design pattern that separates an abstraction from its implementation, allowing the two to vary independently. This pattern is useful in scenarios where you want to avoid a permanent binding between an abstraction and its implementation.
Definition
The Bridge Pattern involves the following components:
- Abstraction: Defines the abstraction's interface.
- Refined Abstraction: Extends the abstraction's interface.
- Implementor: Defines the interface for implementation classes.
- Concrete Implementor: Implements the Implementor interface.
Structure
class Abstraction {
protected Implementor implementor;
public Abstraction(Implementor implementor) {
this.implementor = implementor;
}
public void operation() {
implementor.operationImpl();
}
}
class RefinedAbstraction extends Abstraction {
public RefinedAbstraction(Implementor implementor) {
super(implementor);
}
@Override
public void operation() {
System.out.println("Refined Operation");
implementor.operationImpl();
}
}
interface Implementor {
void operationImpl();
}
class ConcreteImplementorA implements Implementor {
public void operationImpl() {
System.out.println("ConcreteImplementorA operation");
}
}
class ConcreteImplementorB implements Implementor {
public void operationImpl() {
System.out.println("ConcreteImplementorB operation");
}
}
Code Example
public class Main {
public static void main(String[] args) {
Implementor implementorA = new ConcreteImplementorA();
Abstraction abstraction = new RefinedAbstraction(implementorA);
abstraction.operation();
Implementor implementorB = new ConcreteImplementorB();
abstraction = new RefinedAbstraction(implementorB);
abstraction.operation();
}
}
Best Practices
- Use the Bridge Pattern when both the abstraction and the implementation can vary independently.
- Keep the abstraction and implementation separate to enhance flexibility.
- Apply the pattern when the number of subclasses grows large and creates an explosion of classes.
FAQ
What is the main purpose of the Bridge Pattern?
The main purpose of the Bridge Pattern is to decouple an abstraction from its implementation so that they can vary independently.
When should I use the Bridge Pattern?
You should consider using the Bridge Pattern when you want to avoid a permanent binding between an abstraction and its implementation or when both can change independently.
Is the Bridge Pattern similar to the Adapter Pattern?
While both patterns deal with interfaces and implementations, the Bridge Pattern focuses on separating abstraction from implementation, whereas the Adapter Pattern focuses on converting one interface to another.