يعني إيه؟
زي الـ ريموت كنترول! كل زرار بينفذ أمر معين.
ممكن تحفظ الأوامر وتعمل Undo/Redo! ↩️
الريموت مش عارف الجهاز يشتغل إزاي - بس بيضغط على Commands.
كل أمر ملفوف في Object - عنده execute() و ممكن undo()!
الجهاز اللي بينفذ العمل الفعلي - on(), off(), volumeUp().
// Receiver - الجهاز
class TV {
on() { return "📺 TV is ON"; }
off() { return "📺 TV is OFF"; }
volumeUp() { return "🔊 Volume UP"; }
}
// Command Interface
class Command {
execute() { throw "implement!"; }
undo() { throw "implement!"; }
}
// Concrete Commands
class TurnOnCommand extends Command {
constructor(tv) { super(); this.tv = tv; }
execute() { return this.tv.on(); }
undo() { return this.tv.off(); } // الـ Undo!
}
class VolumeUpCommand extends Command {
constructor(tv) { super(); this.tv = tv; }
execute() { return this.tv.volumeUp(); }
}
// Invoker - الريموت
class Remote {
constructor() { this.history = []; }
setCommand(cmd) { this.command = cmd; }
press() {
this.history.push(this.command);
return this.command.execute();
}
undo() {
const cmd = this.history.pop();
return cmd ? cmd.undo() : "Nothing to undo!";
}
}