We are now at the third video of the section command design pattern in the previous video.
We looked at the chain of responsibility design pattern in this video.
We will see how to create a simple Q by implementing the command design pattern to finish with this
section.
We will see also the command pattern a tiny design pattern but still frequently used.
You need a way to connect.
Types that are really unrelated so design a command for them.
The command design pattern is quite similar to the strategy design pattern but with key differences
while in the strategy pattern we focus on changing algorithms in the Command pattern we focus on the
invocation of something or on the abstraction of some type a command pattern is commonly seen as a container
you put something like the info for user interaction on a UI that could be a click on log in and pass
it as a command.
You don't need to have the complexity related to the click on log in action in the command but simply
the action itself.
An example for the organic world would be a box for a delivery company.
We can put anything on it but as a delivery company we are interested in managing the box instead of
its contents directly.
The Command pattern will be used heavily when dealing with channels with channels you can send any message
through it.
But if we need a response from the receiving side of the channel a common approach is to create a command
that has a second response channel attached to where we are listening.
Similarly a good example would be a multiplayer video game where every stroke of each user can be sent
as commands to the rest of the users through the network.
When using the command design pattern we are trying to encapsulate some sort of action or information
in a light package that must be processed somewhere else.
It's similar to the strategy pattern but in fact a command could trigger a pre configured strategy somewhere
else.
So they are not the same.
Here are the objectives for this design pattern to put some information into a box just the receiver
will open the box and know its contents.
Secondly to delegate some action somewhere else.
The behavior is also explained in the diagram on your screen.
There we have a command interface with a get interface method.
We have a type A and Type B.
The idea is that A and B implement the command interface to return themselves as an interface.
As now they implement the command.
They can be used in a command handler which doesn't care very much about the underlying type.
Now a and b can travel through functions that handle commands or store commands freely but to be handler
can take an object from any command handler to unwrap it and take its B content as well as a command
handler with its a content.
We put the information in a box that is the command and delegate what to do with it to the handlers
of commands.
Now let's first understand the example which will be working with on this video.
So it's a simple cue.
Our first example is going to be pretty small.
We will put some information into a command implementer and we will have a cue.
We will create many instances of a type implementing a command pattern and we will pass them to a queue
that will store the commands until three of them are on the queue at which time it will process them.
So the ideal acceptance criteria to understand well the implications of the command should reflect somehow
the creation of a box that can accept unrelated types and the execution of the command itself.
We need a constructor of console printing commands.
When using this constructor with a string it will return a command that will print it.
In this case the handler is inside the command that acts as a box and as a handler we need a data structure
that stores incoming commands in a queue and prints them.
Once the queue reaches the length of 3.
Now let's move on to the implementation.
This pattern is quite simple and we will write a few different examples.
So we'll implement the library directly to keep things light and short.
The classical command design pattern usually has a common type structure with an execute method.
We are also going to use this structure as it is quite flexible and simple.
I have created a folder with the name.
Example 1.
And here I created a file command.
Dot go let's open the file and add the package name important.
F empty and the interface.
This is generic enough to fill a lot of unrelated types.
Think about it.
We are going to create a type that prints to console when using the execute method but it could print
a number or launch a rocket as well.
The key here is to focus on invocations because the handlers are also in command so we need some type.
Implementing this interface and printing to the console.
Some sort of message.
Now let's add the next part of the code.
The console output type implements the command interface and prints to the console.
The member called message as defined in the first acceptance criterion.
We need a command constructor that accepts a message string and returns the commanded face.
It will have the signature function create command as String command.
So that's what we need to add next.
Let me do it.
Call the command Q will define a very simple type called Command Q to store in a Q any type for implementing
the command interface.
Here we are the type.
Command Q done the command Q types those an array of the commands interface.
When the Q array reaches three items it executes all the commands stored in the Q field if it hasn't
reached the required length yet it just stalls the command.
Now we will create five commands enough to trigger the command Q mechanism and add them to the Q Each
time a command is created.
The message creating command will be printed to the console.
When we create the third command the automatic command executor will be launched printing the first
three messages we create and that two commands more because we haven't reached the third command again.
They won't be printed and just creating command messages will be printed.
So here's the function main with the five commands which I just spoke about.
Now let's save this file and run the main program.
Our definition said that the commands are processed once every three messages and we will create a total
of five messages.
The first three messages must be printed but not the fourth and fifth because we didn't reach a sixth
message to trigger the command processing.
It's time to see whether this happens or not.
Run the command go run command dot go enter.
As you can see the fourth and fifth messages aren't printed as expected but we know that the commands
were created and stored on the array.
They just weren't processed because the key was waiting for one command more to trigger the processor.
Now let's talk more examples.
The previous example shows how to use a command handler to execute the contents of the command but a
common way to use a command pattern is to delegate the information instead of the execution to a different
object.
For example instead of printing to the console we will create a command that extract information open
the file command don't go here we first add the package and import f empty and time and add command
interface.
In this case our command interface will have a method named info that will retrieve some information
from its implementer.
We will create two implementations.
One will return the time passed since the creation of the command to its execution.
Let's do it right now.
The time dot since function returns the time elapsed since the time stored in the previous parameter.
We return the string representation of the past time by calling the string method on the time dot time
type.
The second implementation of our new command will return the message Hello world which we are about
to add to the next.
And here it is our main function will simply create an instance of each type.
Then waits for a second and then prints the info returned from each command.
Now let's add the main function here the time dot sleep function stops the execution of the current
go routine for the specified period a second.
So to recall the time command variables stores the time when the program was started and its info method
returns a string representation of the time that passed since we gave a value to the type to the moment
where we called the info method on it.
The helo command variable returns the message Hello world.
When we call it info method here we haven't implemented a command handler again to keep things simple
but we can consider the console as the handler because we can only print ASCII characters on it like
the ones retrieved by the info method now save the file and move on to the terminal let's run the main
function go run command dot go here we are in this case we retrieve some information by using the command
pattern one type stores time information while the other stores nothing and it simply returns the same
simple string each time we run the main function will return a different elapsed time so don't worry
if the time doesn't match with the one in the example do you remember the chain of responsibility design
pattern we were passing a string message between links to print its contents but we could be using the
previous command to retrieve information for logging to the console will mainly reuse the code that
we have written already the command interface will be from the type interface that returns a string
from the previous example I have created a file with the name chain underscore command dot go let's
open it and add the lines of code we need to first declare the package Main and import half empty and
time.
Next we declare the command interface.
Now let's use the command implementation of the time passed.
Type 2.
Okay.
Remember that this type returns the elapsed time from the object creation on its info string method.
We also need the chain logger interface from the chain of responsibility design pattern we used earlier
in this section but this time it will pass commands on its next to method instead of string.
So now we add the chain logger interface.
Now we'll use the same type for two links in the chain for simplicity.
This link is very similar to the first logger type from the chain of responsibility example but this
time it will append the message elapsed time from creation and it will wait one second before printing
we'll call it logger instead of first logger.
Let's add the code for it.
Fine.
Finally we need a main function to execute the chain that takes command pointers.
Let's add it to line by line.
We create a variable called second with a pointer to a logger.
This is going to be the second link in our chain.
Then we create a variable called first that will be the first link in the chain.
The first link points to the second variable.
The second link in the chain.
Then we create an instance of time passed to use it as the command type.
The start time of this command is the execution time the time dot.
Now method returns the time in the moment of the execution.
Finally we pass the command interface to the chain on the first dot.
Next command statement.
We are now ready to see the output of this program.
Let us move to the terminal run the command go run chain command dot go.
The resulting output is reflected in the diagram.
The command with the time field is pushed to the first link that knows how to execute commands of any
type.
Then it passes the command to the second link that also knows how to execute commands.
This approach hides the complexity behind each command execution from the command handlers on each link.
The functionality hidden behind the command can be simple or incredibly complex but the idea here is
to reuse the handler to manage many types of unrelated implementations.
Now let's round up whatever we have learned about the command pattern so command is a very tiny design
pattern.
Its functionality is quite easy to understand but it's widely used for its simplicity.
It looks very similar to the strategy pattern but remember that strategy is about having many algorithms
to achieve some specific task but all of them achieve the same task in the Command pattern.
You can have many tasks to execute and not all of them need to be equal.
So in short the Command pattern is about execution encapsulation and delegation so that just the receiver
or receivers trigger that execution.
In this section we have taken our first steps in the behavioral patterns.
The objective of the section was to introduce you to the concept of algorithm and execution encapsulation
using proper interfaces and structures with the strategy we have encapsulated algorithms with the chain
of responsibility handlers and with the command design pattern executions the chain of responsibility
pattern opens the door of middleware of any type and plug in like libraries to improve the functionality
of some part.
Finally the Command pattern is the most common pattern for UI handling but also very useful in many
other scenarios where we need some type of handling between many unrelated types that are travelling
through the code in the next section.
We will look into template momento and interpreter design patterns.