Command (Behavioral)
Intent / problem it solves
Encapsulate a request as an object, letting you parameterize clients with different requests, queue operations, support undo/redo, and log transactions.
When to use / when NOT
Use for job queues, GUI undo stacks, macro recording, or transactional workflows.
Avoid when a simple function call is enough and you do not need history or scheduling.
Structure
Invoker triggers command; concrete command holds receiver and execute() / undo().
Loading diagram…
Go example
package main
import "fmt"
type Job interface {
Run()
}
type PrintJob struct {
message string
}
func (job PrintJob) Run() { fmt.Println(job.message) }
type Worker struct {
pending []Job
}
func (worker *Worker) Schedule(job Job) { worker.pending = append(worker.pending, job) }
func (worker *Worker) Drain() {
for len(worker.pending) > 0 {
head := worker.pending[0]
worker.pending = worker.pending[1:]
head.Run()
}
}
func main() {
worker := Worker{}
worker.Schedule(PrintJob{"alpha"})
worker.Schedule(PrintJob{"beta"})
worker.Drain()
}JavaScript example
class SaveCommand {
constructor(store, record) {
this.store = store;
this.record = record;
}
execute() {
return this.store.persist(this.record);
}
}
class MemoryStore {
persist(record) {
this.last = record;
return { ok: true, record };
}
}
class Invoker {
constructor() {
this.history = [];
}
run(command) {
const result = command.execute();
this.history.push(command);
return result;
}
}
const invoker = new Invoker();
const store = new MemoryStore();
console.log(invoker.run(new SaveCommand(store, { id: 7 })));Interview phrase
“Command turns an action into an object so I can queue it, retry it, or undo it—essential for job runners and text-editor operations.”
Related LLD case studies
Map to LLD for undo stacks, remote procedure invocation, or task schedulers in LLD case studies.
Last updated on
Spotted something unclear or wrong on this page?