Implementing the Command pattern for different use cases
The Command pattern adds a layer of separation between the request for an action and that action being carried out. The implementation looks like what is shown in Figure 8.2, where the Command
class parent is abstract and only has a constructor, execute()
, and undo()
functions that all take no arguments. The idea is that the child classes are more specific and contain all the object references needed to execute properly:
Figure 8.2 – UML diagram showing the structure of a Command pattern base class
The purpose of a command is to reify the abstract idea of an action so that we can store it in a list. This list can have many uses, but the most identified is the undo queue that Microsoft made synonymous with its keyboard shortcut, Ctrl + Z. When an action is performed, a Command object of the relevant type is created and added to the list. The command is executed and left in this list until it...