+TypeScript example
The buffer performs edits, AppendText retains a target and arguments, and the queue controls execution order. This lets a request be created before the edit actually runs.
class TextBuffer {
#text = "";
get text(): string { return this.#text; }
append(value: string): void { this.#text += value; }
}
interface ICommand { execute(): void; }
// Retain the receiver and arguments in the command for later execution.
class AppendText implements ICommand {
constructor(private readonly buffer: TextBuffer, private readonly value: string) {}
execute(): void { this.buffer.append(this.value); }
}
// The queue manages order through execute without knowing the details of an edit.
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
Enqueueing does not edit the buffer. This synchronous in-memory queue supplies no undo, recovery after failure, or duplicate-execution prevention.