Search This Blog

2023/08/30

Bridge Design Pattern

 // Implementor: Device

class Device {
constructor() {}

isEnabled() {}
enable() {}
disable() {}
getVolume() {}
setVolume(percent) {}
getChannel() {}
setChannel(channel) {}
}

// Concrete Implementor: TV
class TVDevice extends Device {
constructor(name) {
super();
this.enabled = false;
this.volume = 50;
this.channel = 1;
this.name =name;
}

isEnabled() {
return this.enabled;
}

enable() {
this.enabled = true;
}

disable() {
this.enabled = false;
}

getVolume() {
return this.volume;
}

setVolume(percent) {
this.volume = percent;
}

getChannel() {
return this.channel;
}

setChannel(channel) {
this.channel = channel;
}
}

// Concrete Implementor: Radio
class RadioDevice extends Device {
constructor(name) {
super();
this.enabled = false;
this.volume = 30;
this.channel = 100;
this.name = name;
}

isEnabled() {
return this.enabled;
}

enable() {
this.enabled = true;
}

disable() {
this.enabled = false;
}

getVolume() {
return this.volume;
}

setVolume(percent) {
this.volume = percent;
}

getChannel() {
return this.channel;
}

setChannel(channel) {
this.channel = channel;
}
}

// Abstraction: Remote
class Remote {
constructor(device) {
this.device = device;
}

togglePower() {
if (this.device.isEnabled()) {
this.device.disable();
console.log(`on ${this.device.name} Power Down Called`)
} else {
this.device.enable();
console.log(`on ${this.device.name} Power Up Called`)
}
}

volumeUp() {
this.device.setVolume(this.device.getVolume() + 10);
console.log(`on ${this.device.name} volumeUp called`)
}

volumeDown() {
this.device.setVolume(this.device.getVolume() - 10);
console.log(`on ${this.device.name} volumeDown called`)
}

channelUp() {
this.device.setChannel(this.device.getChannel() + 1);
console.log(`on ${this.device.name} channelUp called`)
}

channelDown() {
this.device.setChannel(this.device.getChannel() - 1);
console.log(`on ${this.device.name} channelDown called`)
}
}

// Usage
const tv = new TVDevice('MyTv');
const tvRemote = new Remote(tv);

const radio = new RadioDevice('MyRadio');
const radioRemote = new Remote(radio);

tvRemote.togglePower();
tvRemote.volumeUp();
tvRemote.channelUp();

radioRemote.togglePower();
radioRemote.volumeUp();
radioRemote.channelUp();

No comments:

Post a Comment