class Command {
execute() {
throw new Error('execute가 구현되어야 합니다.');
}
undo() {
throw new Error('undo가 구현되어야 합니다.');
}
}
class AddCommand extends Command {
constructor(receiver, value) {
super();
this.receiver = receiver;
this.value = value;
}
execute() {
this.receiver.add(this.value);
}
undo() {
this.receiver.remove(this.value);
}
}
class RemoveCommand extends Command {
constructor(receiver: Receiver, value) {
super();
this.receiver = receiver;
this.value = value;
}
execute() {
this.receiver.remove(this.value);
}
undo() {
this.receiver.add(this.value);
}
}
class Receiver {
constructor() {
this.items = [];
}
add(item) {
this.items.push(item);
console.log(`item 추가 ${item}`);
}
remove(item) {
const index = this.items.indexOf(item);
if (index !== -1) {
this.items.splice(index, 1);
console.log(`item 삭제 ${item}`);
}
}
}
class Invoker {
constructor() {
this.commands = [];
}
execute(command) {
command.execute();
this.commands.push(command);
}
undo() {
const command = this.commands.pop();
if (command) {
command.undo();
}
}
}
const receiver = new Receiver();
const addCommand = new AddCommand(receiver, 'foo');
const removeCommand = new RemoveCommand(receiver, 'bar');
const invoker = new Invoker();
invoker.execute(addCommand);
invoker.execute(removeCommand);
invoker.undo();