The Bridge pattern is used to separate an abstraction from its implementation, allowing them to vary independently. Here's a breakdown of the key components:
// Abstraction
class RemoteControl {
constructor(device) {
this.device = device;
}
togglePower() {
if (this.device.isEnabled()) {
this.device.disable();
} else {
this.device.enable();
}
}
volumeUp() {
this.device.setVolume(this.device.getVolume() + 10);
}
volumeDown() {
this.device.setVolume(this.device.getVolume() - 10);
}
}
// Refined Abstraction
class AdvancedRemoteControl extends RemoteControl {
mute() {
this.device.setVolume(0);
}
}
// Implementor
class Device {
constructor() {
this.volume = 50;
this.enabled = false;
}
isEnabled() {
return this.enabled;
}
enable() {
this.enabled = true;
}
disable() {
this.enabled = false;
}
getVolume() {
return this.volume;
}
setVolume(volume) {
this.volume = volume;
}
}
// Concrete Implementor
class TV extends Device {
constructor() {
super();
}
// Additional TV-specific methods
}
class Radio extends Device {
constructor() {
super();
}
// Additional Radio-specific methods
}- Abstraction: The
RemoteControlclass acts as the abstraction. It defines the interface for controlling devices but delegates the actual work to thedeviceobject. - Refined Abstraction: The
AdvancedRemoteControlclass extendsRemoteControland adds more functionality, such as themutemethod. - Implementor: The
Deviceclass defines the interface for all concrete devices. It includes methods to enable/disable the device and get/set the volume. - Concrete Implementors: The
TVandRadioclasses extend theDeviceclass and can have additional methods specific to each device type.
const tv = new TV();
const remote = new RemoteControl(tv);
remote.togglePower();
console.log(tv.isEnabled()); // true
remote.volumeUp();
console.log(tv.getVolume()); // 60
const radio = new Radio();
const advancedRemote = new AdvancedRemoteControl(radio);
advancedRemote.togglePower();
console.log(radio.isEnabled()); // true
advancedRemote.mute();
console.log(radio.getVolume()); // 0This pattern decouples an abstraction (RemoteControl) from its implementation (Device) so that the two can vary independently.
RemoteControlis the abstraction that interacts with aDevice.AdvancedRemoteControlis a refined abstraction that adds more functionality.Deviceis the implementor that defines the interface for concrete devices.TVandRadioare concrete implementors that extendDevice.
The Bridge pattern allows you to add new remote controls or devices without changing the existing code, promoting flexibility and scalability.