Bridge = “separate abstraction and implementation so both can change independently”
Adapter: Put old class into a new class implement Interface
Factory Method and Bridge pattern are the same same. Put Interface into Abstract class.
- Factory Method
- Define Interface via abstract method
- Logic call Interface in normal method at Abstract Class
- Bridge pattern:
- Define Interface via Constructor and got Abstract method
- logic call Interface in Concrete class that extends Abstract class
Example
// Implementation hierarchy
interface Device {
void turnOn();
void turnOff();
}
class TV implements Device {
public void turnOn() { System.out.println("TV on"); }
public void turnOff() { System.out.println("TV off"); }
}
class Radio implements Device {
public void turnOn() { System.out.println("Radio on"); }
public void turnOff() { System.out.println("Radio off"); }
}
// Abstraction
abstract class RemoteControl {
protected Device device;
public RemoteControl(Device device) {
this.device = device;
}
abstract void togglePower();
}
// Refined abstraction
class BasicRemote extends RemoteControl {
public BasicRemote(Device device) {
super(device);
}
void togglePower() {
device.turnOn(); // bridge to implementation
}
}