This post gives a brief overview about the Command Pattern. The post is part of a series about software design patterns and their UML representations with the help of PlantUML.
The article aims at providing a very short description of the general idea of the pattern in the first part. This also involves a descriptive UML diagram. Then, the second part provides the PlantUML code for the diagram so that these posts can also be used as a source of design patterns in PlantUML syntax.
What is the Command Pattern?
According to Wikipedia, the Command Pattern is a behavioral design pattern in which an object is used to encapsulate all information needed to perform an action or trigger an event at a later time. This information includes the method name, the object that owns the method and values for the method parameters.
The Command Pattern solves problems like:
- Coupling the invoker of a request to a particular request should be avoided. That is, hard-wired requests should be avoided.
- It should be possible to configure an object (that invokes a request) with a request.
Implementing (hard-wiring) a request directly into a class is inflexible because it couples the class to a particular request at compile-time, which makes it impossible to specify a request at run-time.
What solution does the Command design pattern describe?
- Define separate (command) objects that encapsulate a request.
- A class delegates a request to a command object instead of implementing a particular request directly.
This enables one to configure a class with a command object that is used to perform a request. The class is no longer coupled to a particular request and has no knowledge (is independent) of how the request is carried out.
The following diagram shows the Factory Method Pattern in UML notation. It is based on the corresponding chapter in the book “Head First Design Patterns“:
@startuml class Client class Invoker class Command <<interface>> class Receiver class ConcreteCommand Invoker : setCommand() Command : execute() Command : undo() Receiver : action() ConcreteCommand : execute() ConcreteCommand : undo() Client -> Receiver Client -> ConcreteCommand Receiver <- ConcreteCommand Invoker -> Command Command <|.. ConcreteCommand @enduml
Other Design Patterns
In another article you find information about how to put together a single-side web application using PlantUML.