Skip to content

Instantly share code, notes, and snippets.

@ghazale-javaheri
Created May 27, 2025 16:07
Show Gist options
  • Save ghazale-javaheri/320845d0c13a0838722e3c4f6c11ddc9 to your computer and use it in GitHub Desktop.
Save ghazale-javaheri/320845d0c13a0838722e3c4f6c11ddc9 to your computer and use it in GitHub Desktop.
// Receiver: Lamp
class Lamp {
turnOn() {
console.log("Lamp is ON");
}
turnOff() {
console.log("Lamp is OFF");
}
}
// Smart Home Controller (Tightly Coupled)
class SmartHomeController {
constructor(lamp) {
this.lamp = lamp;
this.history = [];
}
turnOnLamp() {
this.lamp.turnOn();
this.history.push(() => this.lamp.turnOff());
}
turnOffLamp() {
this.lamp.turnOff();
this.history.push(() => this.lamp.turnOn());
}
pressUndo() {
const undo = this.history.pop();
if (undo) undo();
}
}
// Usage
const lamp = new Lamp();
const controller = new SmartHomeController(lamp);
controller.turnOnLamp(); // Lamp is ON
controller.turnOffLamp(); // Lamp is OFF
controller.pressUndo(); // Lamp is ON
controller.pressUndo(); // Lamp is OFF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment