Created
May 27, 2025 16:12
-
-
Save ghazale-javaheri/2b35a41e2dd7f056bb89a4da6bb8c984 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"); | |
} | |
} | |
// Receiver: Music Player | |
class MusicPlayer { | |
playSong(song) { | |
console.log(`Playing song: ${song}`); | |
} | |
stop() { | |
console.log("Music stopped"); | |
} | |
} | |
// Command Interface | |
class Command { | |
execute() {} | |
undo() {} | |
} | |
// Concrete Commands: Lamp | |
class TurnOnLampCommand extends Command { | |
constructor(lamp) { | |
super(); | |
this.lamp = lamp; | |
} | |
execute() { | |
this.lamp.turnOn(); | |
} | |
undo() { | |
this.lamp.turnOff(); | |
} | |
} | |
class TurnOffLampCommand extends Command { | |
constructor(lamp) { | |
super(); | |
this.lamp = lamp; | |
} | |
execute() { | |
this.lamp.turnOff(); | |
} | |
undo() { | |
this.lamp.turnOn(); | |
} | |
} | |
// Concrete Commands: Music Player | |
class PlayMusicCommand extends Command { | |
constructor(musicPlayer, song) { | |
super(); | |
this.musicPlayer = musicPlayer; | |
this.song = song; | |
} | |
execute() { | |
this.musicPlayer.playSong(this.song); | |
} | |
undo() { | |
this.musicPlayer.stop(); | |
} | |
} | |
class StopMusicCommand extends Command { | |
constructor(musicPlayer) { | |
super(); | |
this.musicPlayer = musicPlayer; | |
} | |
execute() { | |
this.musicPlayer.stop(); | |
} | |
// Optional: Could replay last song if stored | |
undo() { | |
console.log("No song to replay"); | |
} | |
} | |
// Invoker: Smart Home Controller | |
class SmartHomeController { | |
constructor() { | |
this.history = []; | |
} | |
pressButton(command) { | |
command.execute(); | |
this.history.push(command); | |
} | |
pressUndo() { | |
const command = this.history.pop(); | |
if (command) { | |
command.undo(); | |
} | |
} | |
} | |
// Usage | |
const lamp = new Lamp(); | |
const musicPlayer = new MusicPlayer(); | |
const controller = new SmartHomeController(); | |
const lampOn = new TurnOnLampCommand(lamp); | |
const lampOff = new TurnOffLampCommand(lamp); | |
const playMusic = new PlayMusicCommand(musicPlayer, "Imagine"); | |
controller.pressButton(lampOn); // Lamp is ON | |
controller.pressButton(playMusic); // Playing song: Imagine | |
controller.pressUndo(); // Music stopped | |
controller.pressUndo(); // Lamp is OFF |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment