Command
Turn a request into an object and queuing, logging, and undo come free. The comparison to hold is with Strategy: both wrap behavior in an object, but Strategy objectifies how something is done while Command objectifies the request itself – which is why only Command gives you an undo stack.
Structure
classDiagram
class Command {
<<interface>>
+execute()
+undo()
}
class ConcreteCommand {
-receiver: Receiver
-args
+execute()
+undo()
}
class Invoker {
-history: List~Command~
+run(c)
+undoLast()
}
class Receiver {
+action()
}
Command <|.. ConcreteCommand
Invoker o--> Command : history
ConcreteCommand o--> Receiver
Telling It Apart
Patterns whose structure looks the same but whose intent does not. See the Confusing Pairs reference.
- Strategy — Encapsulate a family of algorithms as objects and swap them at runtime; the client picks.