In today’s blog, I will be discussing about a design pattern called the Command Design Pattern.
What is a Command Design Pattern?
Command Design Pattern is a behavioral design pattern in which an object is used to represent and encapsulate all the information needed to perform an action or trigger and event at a later time.
How does it work?
The requests are wrapped as commands and passed to invoker object. The invoker object then looks for the appropriate object which can handle this command and gives the command to the corresponding object that will execute this command. The base class contains an execute() method that simply calls the action on the reciever.
A command class includes some of the following: an object, the method to be applied to the object, and the arguments to be passed when the method is applied.
Command Design Pattern allows you to store lists of code that is executed at a later time or many times. Client do not know what the encapsulated objects are, they just call the Command to run when execute is called. An object called the Invoker transfers this command to another object called the receiver to execute the right code.
How to Implement the Command Pattern?
First of, you have to create an interface that acts as a command. Command object knows about the receiver and invokes a method of the receiver.
Second, create your objects(client) that will serve as requests. The client decides which receiver objects it assigns to the command objects, and which commands it assigns to the invoker.
Third, create concrete command classes(also known as the receiver) that implements the command interface which will do the actual work when the execute() method in command is called.
Lastly, create an invoker object to identify which object will execute which command based on the type of command. The invoker object does not know anything about the concrete command, it only knows the command interface.
I selected this post because I wanted to learn more about different patterns that is not covered in class. This post shows you what the Command Pattern is and how it works. It also shows you the different steps and an example code on how to use the command design. The diagram above is from the post.
The Command Pattern seems to be very useful when you found yourself using code that looks like:
if (…..)
do();
else if(……)
do();
else if(……)
do();
else if
……..
I think Command pattern is very useful when you are creating an interface where objects are waiting to be executed, just like the menu interface.
https://www.tutorialspoint.com/design_pattern/command_pattern.htm
From the blog cs-wsu – Computer Science by csrenz and used with permission of the author. All other rights reserved by the author.