Bridge Pattern Demo
package BridgePatternDemo;
// Implementor
interface Car {
void open();
void close();
}
package BridgePatternDemo;
// Concrete Implementors
class Sedan implements Car {
public void open() {
System.out.println("Opening the Sedan's doors.");
}
public void close() {
System.out.println("Closing the Sedan's doors.");
}
}
package BridgePatternDemo;
class SUV implements Car {
public void open() {
System.out.println("Opening the SUV's doors.");
}
public void close() {
System.out.println("Closing the SUV's doors.");
}
}
Driver:
Let's say we have a Remote
class (the Abstraction) that's used by BasicRemote
and AdvancedRemote
classes (the RefinedAbstractions). Remote
controls a Car
(the Implementor), and the Car
class is implemented by Sedan
and SUV
classes (the ConcreteImplementors).
The Bridge pattern lets a BasicRemote
or AdvancedRemote
control either a Sedan
or SUV
interchangeably, and the control methods can be changed independently at runtime.
In the client code, the Car
(implementor) is defined at runtime, which allows you to change the way the Remote
(abstraction) controls the Car
independently of what type of Remote
or Car
it is. The Bridge pattern decouples the two hierarchies and lets them vary independently.