Command Design pattern
Command Pattern is a behavioral design pattern that turns a request into a stand-alone object. This pattern decouples the sender and receiver of the request. It is particularly useful when you want to parameterize objects with operations, queue requests, or allow undo functionality.
Command Pattern Explanation:
In the Command Pattern, the request is encapsulated as an object, allowing for parameterization of clients with queues, requests, and operations. The key components are:
- Command: An interface or abstract class that declares a
execute()
method. - ConcreteCommand: A class that implements the
Command
interface and defines the binding between a receiver and the action. - Invoker: A class that asks the command to execute the request.
- Receiver: A class that knows how to perform the operations associated with the request.
- Client: The class that creates the command and sets its receiver.
Example:
Let’s implement a simple example where the Command Pattern is used to perform actions like turning on and off a light.
1. Command Interface:
2. Concrete Command Classes:
These are concrete implementations of the Command interface, representing actions to be executed.
3. Receiver Class:
The Receiver is the class that actually knows how to perform the action.
4. Invoker Class:
The Invoker is responsible for calling the execute()
method on the command object.
5. Client Code:
Finally, we use the Client to wire everything together and make the requests.
Explanation:
- Command Interface: Defines a method
execute()
, which is implemented by concrete command classes. - ConcreteCommand:
LightOnCommand
andLightOffCommand
implement theexecute()
method. These classes are responsible for invoking the corresponding actions on the Receiver (in this case, theLight
class). - Receiver: The
Light
class has the actual business logic for turning the light on and off. - Invoker: The
RemoteControl
class holds a reference to aCommand
object and callsexecute()
on it when a button is pressed. - Client: The
CommandPatternDemo
class sets everything up by creating the command objects and associating them with the invoker.
Output:
Why Use the Command Pattern?
Decoupling the sender and receiver: The sender (e.g.,
RemoteControl
) doesn't need to know anything about the receiver (e.g.,Light
). It simply callsexecute()
on the command.Extensibility: Adding new commands (like turning the light on in different ways, or adding a fan control) is easy. You can create new command classes without modifying existing code.
Undo/Redo functionality: The Command pattern can be extended to support undo and redo by keeping track of executed commands and their previous states.
Queueing requests: Commands can be queued for execution or logged.
Comments
Post a Comment