Creating coupled commands
Before we dive into writing commands with state data, let’s talk about why they’re necessary. Our reusable commands seem wonderful so far (and well suited to their job), but imagine if you needed to be able to record a sequence of commands and either undo or redo them. Since each reusable command is just a wrapper for its Execute
method, and we pass in a receiver every time we use it, the receiver and the command aren’t bound together. Likewise, if we were to store some values inside the reusable commands, we’d be reusing those values because we’d be reusing the same command instance. You’re seeing the problem, right? To undo a command, we need to know its state before the command is executed. To redo a command, we need to know its starting state.
For our example, we’ll create a new abstract class for movement commands so we can store the unit’s starting and ending positions every time it’...