Created
May 27, 2025 16:07
-
-
Save ghazale-javaheri/320845d0c13a0838722e3c4f6c11ddc9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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