Treating a function call like an object

The biggest benefit of using the Command pattern is that we are encapsulating the function or method call and the parameters. This means that everything needed for the call can be passed to another function, returned from a function, or stored as a variable for later use. This is an extra level of indirection over only using function or method pointers, but it means the client doesn't need to worry about the details. They only need to decide when to execute the command.

This might not seem very useful since we need to know all the function arguments before we pass it to the client. However, this situation can happen more often than you might think. The fact that the client doesn't need to know the details of the function call means that systems such as the UI can be incredibly flexible, and possibly even read from a file.

In the above example, it is obvious that at the time of the call, the client doesn't know which command exists at a given array index. This is by design. What might not be so obvious, is that the array could have been populated using the return value from a function instead of hardcoded calls to a new operator (which we learned in Chapter 5, Decoupling Code via the Factory Method Pattern, leads to inflexible code). This flexibility means that the function to be executed can be changed at runtime.

A perfect example of this is a context sensitive action button in a game. Since there is a limited number of buttons on a gamepad, it is often useful to have the action of button change depending on what the player is doing. This could mean one button is responsible for talking to an NPC, picking up an item, opening a door, or triggering a quick time event depending on the player's location and what they are doing.

Without the Command pattern, the logic involved in organizing, maintaining, and executing all the possible actions in a game would be incredibly complex. With the Command pattern, it is giving every actionable item a command, and making it available when the player is near.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.102.50