+TypeScript 예제
버퍼는 실제 편집을, AppendText는 대상과 인자의 보관을, 큐는 실행 순서를 맡는다. 이렇게 나누면 요청을 만드는 시점과 편집이 일어나는 시점을 서로 다르게 둘 수 있다.
class TextBuffer {
#text = "";
get text(): string { return this.#text; }
append(value: string): void { this.#text += value; }
}
interface ICommand { execute(): void; }
// 나중에 실행할 수 있도록 실제 대상과 인자를 명령 객체에 함께 보관한다.
class AppendText implements ICommand {
constructor(private readonly buffer: TextBuffer, private readonly value: string) {}
execute(): void { this.buffer.append(this.value); }
}
// 큐는 편집 내용을 몰라도 공통 execute 약속으로 실행 순서를 관리한다.
class CommandQueue {
private readonly commands: ICommand[] = [];
add(command: ICommand): void { this.commands.push(command); }
runAll(): void {
for (;;) {
const command = this.commands.shift();
if (command === undefined) return;
command.execute();
}
}
}
const buffer = new TextBuffer();
const queue = new CommandQueue();
queue.add(new AppendText(buffer, "A"));
queue.add(new AppendText(buffer, "B"));
console.log("before: " + buffer.text);
queue.runAll();
console.log("after: " + buffer.text);
before:
after: AB
등록만으로 버퍼가 바뀌지는 않는다. 메모리 안의 동기 큐이며 실행 취소나 장애 뒤 재개·중복 실행 방지는 구현하지 않는다.