Master Software Architecture & Clean Code!
Subscribe to Ram N Java for clean code, design pattern implementations, and practical Java tutorials!
SUBSCRIBE NOWThe Shape & Color Problem in Object-Oriented Design
The Bridge Design Pattern solves one of the most classic challenges in object-oriented programming: class explosion caused by multi-dimensional inheritance. Imagine having geometric shapes (like Circles and Rectangles) and color representations (such as Red and Blue).
Using traditional inheritance, you would need classes like RedCircle, BlueCircle, RedRectangle, and BlueRectangle. If you introduce more shapes or colors, the number of required classes multiplies rapidly. The Bridge pattern breaks this inheritance chain by separating shapes (abstraction) from colors (implementation) using object composition.
Complete Java Code Walkthrough
Here is an end-to-end, clean implementation showing how the Shape abstraction bridges to the Color implementor in Java:
// 1. Implementor Interface
interface Color {
void applyColor();
}
// 2. Concrete Implementors
class RedColor implements Color {
@Override
public void applyColor() {
System.out.println("filled with Red color.");
}
}
class BlueColor implements Color {
@Override
public void applyColor() {
System.out.println("filled with Blue color.");
}
}
// 3. Abstraction (Bridge holding the Implementor reference)
abstract class Shape {
protected Color color;
// Composition Bridge
public Shape(Color color) {
this.color = color;
}
public abstract void draw();
}
// 4. Refined Abstractions
class Circle extends Shape {
public Circle(Color color) {
super(color);
}
@Override
public void draw() {
System.out.print("Drawing Circle ");
color.applyColor();
}
}
class Rectangle extends Shape {
public Rectangle(Color color) {
super(color);
}
@Override
public void draw() {
System.out.print("Drawing Rectangle ");
color.applyColor();
}
}
// 5. Client Application
public class BridgeShapeDemo {
public static void main(String[] args) {
// Red Circle
Shape redCircle = new Circle(new RedColor());
redCircle.draw();
// Blue Rectangle
Shape blueRectangle = new Rectangle(new BlueColor());
blueRectangle.draw();
// Blue Circle (flexible composition without subclassing!)
Shape blueCircle = new Circle(new BlueColor());
blueCircle.draw();
}
}
Key Architectural Advantages
- Prevents Combinatorial Explosion: Adding
Nshapes andMcolors requires onlyN + Mclasses instead ofN × Mclasses. - Composition Over Inheritance: Connects abstraction and implementor dynamically at runtime rather than locking them down at compile time.
- Strict Adherence to Open/Closed Principle: New shapes or new color implementations can be introduced without modifying existing codebase components.
Watch More Related Design Pattern Tutorials
Click here to watch in Youtube : https://www.youtube.com/watch?v=bBcrJ_ivwnE
Click the below Image to Enlarge
| Bridge Design pattern - Real time example [Shape] |
No comments:
Post a Comment