Bridge = “separate abstraction and implementation so both can change independently”
- Bridge pattern:
- TV, Radio implement Device got turnOn, turnOff method.
- Abstract RemoteControl got abstract method
togglePowerand interface Device via constructor - Concrete class override togglePower by device.turnOff
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
}
}
Usage
public static void main(String[] args) {
BasicRemote remote = new BasicRemote(new TV());
remote.tooglePower();
remote = new BasicRemote(new Radio());
remote.tooglePower();
}