BridgePattern decouples an abstraction from its implementation.
Abstraction and Implementation can vary independently since the concrete class does not directly implement Abstraction ( interface)
Key note: Two orthogonal class hierarchies (The Abstraction hierarchy and Implementation hierarchy) are linked using composition (and not inheritance).This composition helps both hierarchies to vary independently.
Implementation never refers Abstraction. Abstraction contains Implementation interface as a member (through composition).
Coming back to your question regarding the example code in journaldev article :
Shape is Abstraction
Triangle is RedefinedAbstraction
Color is Implementor
RedColor is ConcreteImplementor
A concrete Shape object : Triangle extends Shape but does not implement the Color interface.
public class Triangle extends Shape{
}
RedColor and GreenColor actually implement the Color interface.
The Concrete Shape object (Triangle) is independent of implementing abstraction (i.e. Color interface).
Shape tri = new Triangle(new RedColor());
Here Triangle contains a concrete Color object ( Composition). If there is a change in the Color abstraction (interface), RedColor and GreenColor are responsible for implementing the abstraction of Color interface.
Shapes like Triangle is not affected by changes in contract to the Color interface. So the Color interface can vary independently. This is possible because Shape holds the contract that uses Composition rather than implementation.
In Summary,
- Bridge is a structural pattern
- Abstraction and implementation are not bound at compile time
- Abstraction and implementation - both can vary without impact in client
Use the Bridge pattern when:
- You want run-time binding of the implementation,
- You have a proliferation of classes from a coupled interface and numerous implementations,
- You want to share an implementation among multiple objects,
- You need to map orthogonal class hierarchies.
Useful links:
tutorialspoint artice
dzone article
oodesign article
sourcemaking article
Related post:
When do you use the Bridge Pattern? How is it different from Adapter pattern?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…