Design Pattern: Command
in object-oriented programming, the command pattern is a behavioral pattern that allows encapsulating the information needed to perform an action or trigger an event at a later time.
to realize this pattern I will use a small example with some cubes that will change color, in this case, I will use the command pattern to record the actions of changing color. I will do it in such a way that it can be executed in reverse so each action will have the command in normal and the one to go back.
Let’s move on to the implementation, we should make an interface that we will use to create the commands, the commands that we want to create, a command manager, and finally the script that the end-user will use.
As a first thing, I have to define an interface that will implement my actions.
Let’s move on to the commands, in this case, I want to create a command that when the mouse clicks will change the color of the cube that I have selected.
I need to create a class that implements the interface and that has a class constructor to store the reference from the object with which we will use it. At this point, we are going to write the behavior of the Execute and Undo methods.
The third part is the one that is a bit longer you have to write the command manager, to do this I will use the lists to create a sequence of commands and also easily create the inverted version.
As always being a manager I will use the singleton to make it accessible as an instance, then I will have a method to add the commands that are called to the list of ICommand, and finally, I will write the behavior for the buttons of the UI that I am using in this example.
The confirm command will complete the registration of the commands and bring the cubes to the initial color.
The reset will empty the list.
Finally, the play and rewind commands will scroll through the list of actions.
Finally, we have to build the input for the final user. In this case, I used the mouse pointer and a raycast and I made sure to give a tag to the cubes I’m using.
When to use it
This pattern makes a little longer the construction of inputs but allows us to create a system that we often see in strategic games, my example is an end in itself but we can also use it to create sequences of animations or in other situations where it may be useful to store the various steps.
I hope it can be useful, happy 2022!