Understanding the Bridge Design Pattern: Concepts, Java Implementation, and Use Cases
This article explains the Bridge design pattern, a structural pattern that separates abstraction from implementation to avoid class explosion, provides detailed Java code examples, UML diagrams, advantages, disadvantages, and typical scenarios for applying the pattern in software development.
Bridge pattern is a structural design pattern that separates abstraction from implementation, allowing them to vary independently.
Motivation: when combining multiple dimensions (e.g., fruit types and colors) leads to exponential class explosion, bridge replaces inheritance with composition.
Structure: Abstraction, Refined Abstraction, Implementor, Concrete Implementor. UML diagram illustrates the relationships.
Java example:
public interface ColorAPI {
void paint();
}
public class YellowColorAPI implements ColorAPI {
@Override
public void paint() {
System.out.println("添加黄色");
}
}
public class RedColorAPI implements ColorAPI {
@Override
public void paint() {
System.out.println("添加红色");
}
}
public abstract class Fruit {
protected ColorAPI colorAPI;
public void setDrawAPI(ColorAPI colorAPI) { this.colorAPI = colorAPI; }
public abstract void draw();
}
public class Apple extends Fruit {
@Override
public void draw() {
System.out.print("我是苹果");
colorAPI.paint();
}
}
public class Banana extends Fruit {
@Override
public void draw() {
System.out.print("我是香蕉");
colorAPI.paint();
}
}
public class Client {
public static void main(String[] args) {
Fruit fruit = new Apple();
fruit.setDrawAPI(new RedColorAPI());
fruit.draw();
Fruit fruit1 = new Banana();
fruit1.setDrawAPI(new YellowColorAPI());
fruit1.draw();
}
}Output:
我是苹果画上红色
我是香蕉画上黄色Adding a new fruit or a new color only requires creating a new subclass without modifying existing hierarchies.
Advantages: decouples abstraction and implementation, follows the Open/Closed principle and composition over inheritance, and keeps implementation details transparent to clients.
Disadvantages: requires careful identification of independent dimensions, which can increase design complexity.
Typical scenarios: multiple implementations that should not affect clients, need to decouple abstraction from implementation, or require flexible switching and combination of different abstractions and implementations.
When applying the pattern, consider using factories or dependency injection to create and inject the appropriate objects.
Mike Chen's Internet Architecture
Over ten years of BAT architecture experience, shared generously!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.