The Command Pattern is a behavioral design pattern that encapsulates a request as an object, thereby allowing you to parameterize objects with requests, delay their execution, or support undoable operations.
The Command Pattern encapsulates a request as an object. It separates the object that invokes the operation from the one that knows how to perform it.
Key features:
- Encapsulation: Encapsulates a request as an object.
- Decoupling: Decouples the invoker and the receiver.
- Undo/Redo: Provides support for undoable operations.
The implementation of the Command Pattern can be found in:
Command.java
: The interface for all commands.Light.java
: The receiver class.LightOnCommand.java
,LightOffCommand.java
: Concrete command implementations.RemoteControl.java
: The invoker class.Main.java
: Demonstrates the usage of the Command Pattern.
To see the Command Pattern in action, refer to the Main.java
file. It demonstrates controlling a light using commands.
classDiagram
direction LR
class Client {
}
class Invoker {
}
class Command {
+Execute()
}
class ConcreteCommand {
-state
+Execute()
}
class Receiver {
+Action()
}
Client --> Invoker
Invoker o--> Command
Command <|-- ConcreteCommand
ConcreteCommand --> Receiver : receiver
Client --> Receiver
Client --> ConcreteCommand
Note
If the UML above is not rendering correctly, you can view the diagram from the command_uml.png
file.
- The Command Pattern encapsulates a request as an object, allowing you to parameterize objects with requests.
- It decouples the invoker from the receiver, providing support for undoable operations.
- Use it when you need to support operations such as undo, redo, or queuing requests.