Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ghazale-javaheri/31109aff06b39afd884a842bf3cfbefd to your computer and use it in GitHub Desktop.
Save ghazale-javaheri/31109aff06b39afd884a842bf3cfbefd to your computer and use it in GitHub Desktop.
// Receivers: Devices
class Light {
turnOn() {
console.log("Lights are ON");
}
turnOff() {
console.log("Lights are OFF");
}
}
class MusicPlayer {
playSong(song) {
console.log(`Playing song: ${song}`);
}
stop() {
console.log("Music stopped");
}
}
// Smart Home Controller (Tightly Coupled)
class SmartHomeController {
constructor(light, musicPlayer) {
this.light = light;
this.musicPlayer = musicPlayer;
this.history = [];
}
// Light Controls
turnOnLight() {
this.light.turnOn();
this.history.push(() => this.light.turnOff());
}
turnOffLight() {
this.light.turnOff();
this.history.push(() => this.light.turnOn());
}
// Music Controls
playMusic(song) {
this.musicPlayer.playSong(song);
this.history.push(() => this.musicPlayer.stop());
}
stopMusic() {
this.musicPlayer.stop();
// No undo for stop unless we track previous song manually!
}
// Undo last action
pressUndo() {
const undo = this.history.pop();
if (undo) undo();
}
}
// Usage
const light = new Light();
const musicPlayer = new MusicPlayer();
const controller = new SmartHomeController(light, musicPlayer);
controller.turnOnLight(); // Lights are ON
controller.playMusic("Imagine"); // Playing song: Imagine
controller.pressUndo(); // Music stopped
controller.pressUndo(); // Lights are OFF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment