Design Pattern | Command Pattern

What Is the Command Pattern?

  • Command means instruction.
  • The Command pattern represents a command as an instance of a class.
  • When you want to manage command history, you manage a collection of those instances. By storing commands, the same command can be executed again, or several commands can be combined and reused as a new command.
  • In GoF design patterns, it is classified as a behavioral design pattern.

Command Pattern Example Program

The example is a simple drawing program.

Class Diagram
Command Pattern Class Diagram

The example defines a Command interface with execute(), a history object that stores commands, drawable targets, drawing commands, and UI classes that create and replay drawing operations. Each drawing action is captured as an object, so it can be executed, stored, replayed, or grouped.

Advantages

Commands can be treated as data. This makes it easier to implement histories, undo/redo, macro commands, queues, logging, and delayed execution while keeping the requester independent from the actual receiver.