-
Notifications
You must be signed in to change notification settings - Fork 513
Expand file tree
/
Copy pathcommand.html
More file actions
541 lines (508 loc) · 39.8 KB
/
command.html
File metadata and controls
541 lines (508 loc) · 39.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
<title>Command · Design Patterns Revisited · Game Programming Patterns</title>
<!-- Tell mobile browsers we're optimized for them and they don't need to crop
the viewport. -->
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="stylesheet" type="text/css" href="style.css" />
<link href="https://fonts.googleapis.com/css?family=Merriweather:400,400italic,700,700italic|Source+Code+Pro|Source+Sans+Pro:200,300,400,600,400italic,600italic|Rock+Salt" rel="stylesheet" type="text/css">
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-42804721-1', 'gameprogrammingpatterns.com');
ga('send', 'pageview');
</script>
<script src="jquery-3.6.0.min.js"></script>
<script src="script.js"></script>
</head>
<body id="top">
<div class="page sidebar">
<span class="theme-toggler" title="dark theme" onclick="toggleTheme()"></span>
<div class="content">
<nav class="top">
<span class="prev">← <a href="design-patterns-revisited.html">Previous Chapter</a></span>
<span class="next"><a href="flyweight.html">Next Chapter</a> →</span>
<span class="toc">≡ <a href="/">The Book</a></span>
</nav>
<h1>Command</h1>
<h1 class="book"><a href="/">Game Programming Patterns</a><span class="section"><a href="design-patterns-revisited.html">Design Patterns Revisited</a></span></h1>
<p>Command is one of my favorite patterns. Most large programs I write, games or
otherwise, end up using it somewhere. When I’ve used it in the right place, it’s
neatly untangled some really gnarly code. For such a swell pattern, the Gang of
Four has a predictably abstruse description:</p>
<blockquote>
<p>Encapsulate a request as an object, thereby letting users parameterize clients
with different requests, queue or log requests, and support undoable
operations.</p>
</blockquote>
<p>I think we can all agree that that’s a terrible sentence. First of all, it
mangles whatever metaphor it’s trying to establish. Outside of the weird world
of software where words can mean anything, a “client” is a <em>person</em> — someone
you do business with. Last I checked, human beings can’t be “parameterized”.</p>
<p>Then, the rest of that sentence is just a list of stuff you could maybe possibly
use the pattern for. Not very illuminating unless your use case happens to be in
that list. <em>My</em> pithy tagline for the Command pattern is:</p>
<p><strong>A command is a <em><span name="latin">reified</span> method call</em>.</strong></p>
<aside name="latin">
<p>“Reify” comes from the Latin “res”, for “thing”, with the English suffix
“–fy”. So it basically means “thingify”, which, honestly, would be a more
fun word to use.</p>
</aside>
<p>Of course, “pithy” often means “impenetrably terse”, so this may not be much of
an improvement. Let me unpack that a bit. “Reify”, in case you’ve never heard
it, means “make real”. Another term for reifying is making something “first-class”.</p>
<aside name="reflection">
<p><em>Reflection systems</em> in some languages let you work with the types in your
program imperatively at runtime. You can get an object that represents the class
of some other object, and you can play with that to see what the type can do. In
other words, reflection is a <em>reified type system</em>.</p>
</aside>
<p>Both terms mean taking some <span name="reflection"><em>concept</em></span> and turning
it into a piece of <em>data</em> — an object — that you can stick in a variable, pass
to a function, etc. So by saying the Command pattern is a “reified method call”,
what I mean is that it’s a method call wrapped in an object.</p>
<p>That sounds a lot like a “callback”, “first-class function”, “function pointer”,
“closure”, or “partially applied function” depending on which language you’re
coming from, and indeed those are all in the same ballpark. The Gang of Four
later says:</p>
<blockquote>
<p>Commands are an object-oriented replacement for callbacks.</p>
</blockquote>
<p>That would be a better slugline for the pattern than the one they chose.</p>
<p>But all of this is abstract and nebulous. I like to start chapters with
something concrete, and I blew that. To make up for it, from here on out it’s
all examples where commands are a brilliant fit.</p>
<h2><a href="#configuring-input" name="configuring-input">Configuring Input</a></h2>
<p>Somewhere in every game is a chunk of code that reads in raw user input —
button presses, keyboard events, mouse clicks, whatever. It takes each input and
translates it to a meaningful action in the game:</p>
<p><img src="images/command-buttons-one.png" alt="A controller, with A mapped to swapWeapon(), B mapped to lurch(), X mapped to jump(), and Y mapped to fireGun()." /></p>
<p>A dead simple implementation looks like:</p>
<p><span name="lurch"></span></p>
<div class="codehilite"><pre><span></span><code><span class="kt">void</span> <span class="nf">InputHandler::handleInput</span><span class="p">()</span>
<span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="n">isPressed</span><span class="p">(</span><span class="n">BUTTON_X</span><span class="p">))</span> <span class="n">jump</span><span class="p">();</span>
<span class="k">else</span> <span class="k">if</span> <span class="p">(</span><span class="n">isPressed</span><span class="p">(</span><span class="n">BUTTON_Y</span><span class="p">))</span> <span class="n">fireGun</span><span class="p">();</span>
<span class="k">else</span> <span class="k">if</span> <span class="p">(</span><span class="n">isPressed</span><span class="p">(</span><span class="n">BUTTON_A</span><span class="p">))</span> <span class="n">swapWeapon</span><span class="p">();</span>
<span class="k">else</span> <span class="k">if</span> <span class="p">(</span><span class="n">isPressed</span><span class="p">(</span><span class="n">BUTTON_B</span><span class="p">))</span> <span class="n">lurchIneffectively</span><span class="p">();</span>
<span class="p">}</span>
</code></pre></div>
<aside name="lurch">
<p>Pro tip: Don’t press B very often.</p>
</aside>
<p>This function typically gets called once per frame by the <a class="pattern"
href="game-loop.html">Game Loop</a>, and I’m sure you can figure out what it
does. This code works if we’re willing to hard-wire user inputs to game actions,
but many games let the user <em>configure</em> how their buttons are mapped.</p>
<p>To support that, we need to turn those direct calls to <code>jump()</code> and <code>fireGun()</code>
into something that we can swap out. “Swapping out” sounds a lot like assigning
a variable, so we need an <em>object</em> that we can use to represent a game action.
Enter: the Command pattern.</p>
<p>We define a base class that represents a triggerable game command:</p>
<p><span name="one-method"></span></p>
<div class="codehilite"><pre><span></span><code><span class="k">class</span> <span class="nc">Command</span>
<span class="p">{</span>
<span class="k">public</span><span class="o">:</span>
<span class="k">virtual</span> <span class="o">~</span><span class="n">Command</span><span class="p">()</span> <span class="p">{}</span>
<span class="k">virtual</span> <span class="kt">void</span> <span class="n">execute</span><span class="p">()</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">};</span>
</code></pre></div>
<aside name="one-method">
<p>When you have an interface with a single method that doesn’t return anything,
there’s a good chance it’s the Command pattern.</p>
</aside>
<p>Then we create subclasses for each of the different game actions:</p>
<div class="codehilite"><pre><span></span><code><span class="k">class</span> <span class="nc">JumpCommand</span> <span class="o">:</span> <span class="k">public</span> <span class="n">Command</span>
<span class="p">{</span>
<span class="k">public</span><span class="o">:</span>
<span class="k">virtual</span> <span class="kt">void</span> <span class="n">execute</span><span class="p">()</span> <span class="p">{</span> <span class="n">jump</span><span class="p">();</span> <span class="p">}</span>
<span class="p">};</span>
<span class="k">class</span> <span class="nc">FireCommand</span> <span class="o">:</span> <span class="k">public</span> <span class="n">Command</span>
<span class="p">{</span>
<span class="k">public</span><span class="o">:</span>
<span class="k">virtual</span> <span class="kt">void</span> <span class="n">execute</span><span class="p">()</span> <span class="p">{</span> <span class="n">fireGun</span><span class="p">();</span> <span class="p">}</span>
<span class="p">};</span>
<span class="c1">// You get the idea...</span>
</code></pre></div>
<p>In our input handler, we store a pointer to a command for each button:</p>
<div class="codehilite"><pre><span></span><code><span class="k">class</span> <span class="nc">InputHandler</span>
<span class="p">{</span>
<span class="k">public</span><span class="o">:</span>
<span class="kt">void</span> <span class="n">handleInput</span><span class="p">();</span>
<span class="c1">// Methods to bind commands...</span>
<span class="k">private</span><span class="o">:</span>
<span class="n">Command</span><span class="o">*</span> <span class="n">buttonX_</span><span class="p">;</span>
<span class="n">Command</span><span class="o">*</span> <span class="n">buttonY_</span><span class="p">;</span>
<span class="n">Command</span><span class="o">*</span> <span class="n">buttonA_</span><span class="p">;</span>
<span class="n">Command</span><span class="o">*</span> <span class="n">buttonB_</span><span class="p">;</span>
<span class="p">};</span>
</code></pre></div>
<p>Now the input handling just delegates to those:</p>
<p><span name="null"></span></p>
<div class="codehilite"><pre><span></span><code><span class="kt">void</span> <span class="nf">InputHandler::handleInput</span><span class="p">()</span>
<span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="n">isPressed</span><span class="p">(</span><span class="n">BUTTON_X</span><span class="p">))</span> <span class="n">buttonX_</span><span class="o">-></span><span class="n">execute</span><span class="p">();</span>
<span class="k">else</span> <span class="k">if</span> <span class="p">(</span><span class="n">isPressed</span><span class="p">(</span><span class="n">BUTTON_Y</span><span class="p">))</span> <span class="n">buttonY_</span><span class="o">-></span><span class="n">execute</span><span class="p">();</span>
<span class="k">else</span> <span class="k">if</span> <span class="p">(</span><span class="n">isPressed</span><span class="p">(</span><span class="n">BUTTON_A</span><span class="p">))</span> <span class="n">buttonA_</span><span class="o">-></span><span class="n">execute</span><span class="p">();</span>
<span class="k">else</span> <span class="k">if</span> <span class="p">(</span><span class="n">isPressed</span><span class="p">(</span><span class="n">BUTTON_B</span><span class="p">))</span> <span class="n">buttonB_</span><span class="o">-></span><span class="n">execute</span><span class="p">();</span>
<span class="p">}</span>
</code></pre></div>
<aside name="null">
<p>Notice how we don’t check for <code>NULL</code> here? This assumes each button will have
<em>some</em> command wired up to it.</p>
<p>If we want to support buttons that do nothing without having to explicitly check
for <code>NULL</code>, we can define a command class whose <code>execute()</code> method does nothing.
Then, instead of setting a button handler to <code>NULL</code>, we point it to that object.
This is a pattern called <a href="http://en.wikipedia.org/wiki/Null_Object_pattern">Null
Object</a>.</p>
</aside>
<p>Where each input used to directly call a function, now there’s a layer of
indirection:</p>
<p><img src="images/command-buttons-two.png" alt="A controller, with each button mapped to a corresponding 'button_' variable which in turn is mapped to a function." /></p>
<p>This is the Command pattern in a nutshell. If you can see the merit of it
already, consider the rest of this chapter a bonus.</p>
<h2><a href="#directions-for-actors" name="directions-for-actors">Directions for Actors</a></h2>
<p>The command classes we just defined work for the previous example, but they’re
pretty limited. The problem is that they assume there are these top-level
<code>jump()</code>, <code>fireGun()</code>, etc. functions that implicitly know how to find the
player’s avatar and make him dance like the puppet he is.</p>
<p>That assumed coupling limits the usefulness of those commands. The <em>only</em> thing
the <code>JumpCommand</code> can make jump is the player. Let’s loosen that restriction.
Instead of calling functions that find the commanded object themselves, we’ll
<em>pass in</em> the object that we want to order around:</p>
<div class="codehilite"><pre><span></span><code><span class="k">class</span> <span class="nc">Command</span>
<span class="p">{</span>
<span class="k">public</span><span class="o">:</span>
<span class="k">virtual</span> <span class="o">~</span><span class="n">Command</span><span class="p">()</span> <span class="p">{}</span>
<span class="k">virtual</span> <span class="kt">void</span> <span class="n">execute</span><span class="p">(</span><span class="n">GameActor</span><span class="o">&</span> <span class="n">actor</span><span class="p">)</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">};</span>
</code></pre></div>
<p>Here, <code>GameActor</code> is our “game object” class that represents a character in the
game world. We pass it in to <code>execute()</code> so that the derived command can invoke
methods on an actor of our choice, like so:</p>
<div class="codehilite"><pre><span></span><code><span class="k">class</span> <span class="nc">JumpCommand</span> <span class="o">:</span> <span class="k">public</span> <span class="n">Command</span>
<span class="p">{</span>
<span class="k">public</span><span class="o">:</span>
<span class="k">virtual</span> <span class="kt">void</span> <span class="n">execute</span><span class="p">(</span><span class="n">GameActor</span><span class="o">&</span> <span class="n">actor</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">actor</span><span class="p">.</span><span class="n">jump</span><span class="p">();</span>
<span class="p">}</span>
<span class="p">};</span>
</code></pre></div>
<p>Now, we can use this one class to make any character in the game hop around.
We’re just missing a piece between the input handler and the command that takes
the command and invokes it on the right object. First, we change <code>handleInput()</code>
so that it <em>returns</em> commands:</p>
<div class="codehilite"><pre><span></span><code><span class="n">Command</span><span class="o">*</span> <span class="nf">InputHandler::handleInput</span><span class="p">()</span>
<span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="n">isPressed</span><span class="p">(</span><span class="n">BUTTON_X</span><span class="p">))</span> <span class="k">return</span> <span class="n">buttonX_</span><span class="p">;</span>
<span class="k">if</span> <span class="p">(</span><span class="n">isPressed</span><span class="p">(</span><span class="n">BUTTON_Y</span><span class="p">))</span> <span class="k">return</span> <span class="n">buttonY_</span><span class="p">;</span>
<span class="k">if</span> <span class="p">(</span><span class="n">isPressed</span><span class="p">(</span><span class="n">BUTTON_A</span><span class="p">))</span> <span class="k">return</span> <span class="n">buttonA_</span><span class="p">;</span>
<span class="k">if</span> <span class="p">(</span><span class="n">isPressed</span><span class="p">(</span><span class="n">BUTTON_B</span><span class="p">))</span> <span class="k">return</span> <span class="n">buttonB_</span><span class="p">;</span>
<span class="c1">// Nothing pressed, so do nothing.</span>
<span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div>
<p>It can’t execute the command immediately since it doesn’t know what actor to
pass in. Here’s where we take advantage of the fact that the command is a
reified call — we can <em>delay</em> when the call is executed.</p>
<p>Then, we need some code that takes that command and runs it on the actor
representing the player. Something like:</p>
<div class="codehilite"><pre><span></span><code><span class="n">Command</span><span class="o">*</span> <span class="n">command</span> <span class="o">=</span> <span class="n">inputHandler</span><span class="p">.</span><span class="n">handleInput</span><span class="p">();</span>
<span class="k">if</span> <span class="p">(</span><span class="n">command</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">command</span><span class="o">-></span><span class="n">execute</span><span class="p">(</span><span class="n">actor</span><span class="p">);</span>
<span class="p">}</span>
</code></pre></div>
<p>Assuming <code>actor</code> is a reference to the player’s character, this correctly drives
him based on the user’s input, so we’re back to the same behavior we had in the
first example. But adding a layer of indirection between the command and the
actor that performs it has given us a neat little ability: <em>we can let the
player control any actor in the game now by changing the actor we execute
the commands on.</em></p>
<p>In practice, that’s not a common feature, but there is a similar use case that
<em>does</em> pop up frequently. So far, we’ve only considered the player-driven
character, but what about all of the other actors in the world? Those are driven
by the game’s AI. We can use this same command pattern as the interface between
the AI engine and the actors; the AI code simply emits <code>Command</code> objects.</p>
<p>The decoupling here between the AI that selects commands and the actor code
that performs them gives us a lot of flexibility. We can use different AI
modules for different actors. Or we can mix and match AI for different kinds of
behavior. Want a more aggressive opponent? Just plug-in a more aggressive AI to
generate commands for it. In fact, we can even bolt AI onto the <em>player’s</em>
character, which can be useful for things like demo mode where the game needs to
run on auto-pilot.</p>
<p><span name="queue">By</span> making the commands that control an actor
first-class objects, we’ve removed the tight coupling of a direct method call.
Instead, think of it as a queue or stream of commands:</p>
<aside name="queue">
<p>For lots more on what queueing can do for you, see <a href="event-queue.html"
class="pattern">Event Queue</a>.</p>
</aside>
<p><span name="stream"></span></p>
<p><img src="images/command-stream.png" alt="A pipe connecting AI to Actor." /></p>
<aside name="stream">
<p>Why did I feel the need to draw a picture of a “stream” for you? And why does it
look like a tube?</p>
</aside>
<p>Some code (the input handler or AI) <span name="network">produces</span>
commands and places them in the stream. Other code (the dispatcher or actor
itself) consumes commands and invokes them. By sticking that queue in the
middle, we’ve decoupled the producer on one end from the consumer on the other.</p>
<aside name="network">
<p>If we take those commands and make them <em>serializable</em>, we can send the stream
of them over the network. We can take the player’s input, push it over the
network to another machine, and then replay it. That’s one important piece of
making a networked multi-player game.</p>
</aside>
<h2><a href="#undo-and-redo" name="undo-and-redo">Undo and Redo</a></h2>
<p>The final example is the most well-known use of this pattern. If a command object
can <em>do</em> things, it’s a small step for it to be able to <em>undo</em> them. Undo is
used in some strategy games where you can roll back moves that you didn’t like.
It’s <em>de rigueur</em> in tools that people use to <em>create</em> games. The <span
name="hate">surest way</span> to make your game designers hate you is giving
them a level editor that can’t undo their fat-fingered mistakes.</p>
<aside name="hate">
<p>I may be speaking from experience here.</p>
</aside>
<p>Without the Command pattern, implementing undo is surprisingly hard. With it,
it’s a piece of cake. Let’s say we’re making a single-player, turn-based game and
we want to let users undo moves so they can focus more on strategy and less on
guesswork.</p>
<p>We’re conveniently already using commands to abstract input handling, so every
move the player makes is already encapsulated in them. For example, moving a
unit may look like:</p>
<div class="codehilite"><pre><span></span><code><span class="k">class</span> <span class="nc">MoveUnitCommand</span> <span class="o">:</span> <span class="k">public</span> <span class="n">Command</span>
<span class="p">{</span>
<span class="k">public</span><span class="o">:</span>
<span class="n">MoveUnitCommand</span><span class="p">(</span><span class="n">Unit</span><span class="o">*</span> <span class="n">unit</span><span class="p">,</span> <span class="kt">int</span> <span class="n">x</span><span class="p">,</span> <span class="kt">int</span> <span class="n">y</span><span class="p">)</span>
<span class="o">:</span> <span class="n">unit_</span><span class="p">(</span><span class="n">unit</span><span class="p">),</span>
<span class="n">x_</span><span class="p">(</span><span class="n">x</span><span class="p">),</span>
<span class="n">y_</span><span class="p">(</span><span class="n">y</span><span class="p">)</span>
<span class="p">{}</span>
<span class="k">virtual</span> <span class="kt">void</span> <span class="n">execute</span><span class="p">()</span>
<span class="p">{</span>
<span class="n">unit_</span><span class="o">-></span><span class="n">moveTo</span><span class="p">(</span><span class="n">x_</span><span class="p">,</span> <span class="n">y_</span><span class="p">);</span>
<span class="p">}</span>
<span class="k">private</span><span class="o">:</span>
<span class="n">Unit</span><span class="o">*</span> <span class="n">unit_</span><span class="p">;</span>
<span class="kt">int</span> <span class="n">x_</span><span class="p">,</span> <span class="n">y_</span><span class="p">;</span>
<span class="p">};</span>
</code></pre></div>
<p>Note this is a little different from our previous commands. In the last example,
we wanted to <em>abstract</em> the command from the actor that it modified. In this
case, we specifically want to <em>bind</em> it to the unit being moved. An instance of
this command isn’t a general “move something” operation that you could use in a
bunch of contexts; it’s a specific concrete move in the game’s sequence of
turns.</p>
<p>This highlights a variation in how the Command pattern gets implemented. In some
cases, like our first couple of examples, a command is a reusable object that
represents a <em>thing that can be done</em>. Our earlier input handler held on to a
single command object and called its <code>execute()</code> method anytime the right button
was pressed.</p>
<p>Here, the commands are more specific. They represent a thing that can be done at
a specific point in time. This means that the input handling code will be <span
name="free"><em>creating</em></span> an instance of this every time the player chooses
a move. Something like:</p>
<div class="codehilite"><pre><span></span><code><span class="n">Command</span><span class="o">*</span> <span class="nf">handleInput</span><span class="p">()</span>
<span class="p">{</span>
<span class="n">Unit</span><span class="o">*</span> <span class="n">unit</span> <span class="o">=</span> <span class="n">getSelectedUnit</span><span class="p">();</span>
<span class="k">if</span> <span class="p">(</span><span class="n">isPressed</span><span class="p">(</span><span class="n">BUTTON_UP</span><span class="p">))</span> <span class="p">{</span>
<span class="c1">// Move the unit up one.</span>
<span class="kt">int</span> <span class="n">destY</span> <span class="o">=</span> <span class="n">unit</span><span class="o">-></span><span class="n">y</span><span class="p">()</span> <span class="o">-</span> <span class="mi">1</span><span class="p">;</span>
<span class="k">return</span> <span class="k">new</span> <span class="n">MoveUnitCommand</span><span class="p">(</span><span class="n">unit</span><span class="p">,</span> <span class="n">unit</span><span class="o">-></span><span class="n">x</span><span class="p">(),</span> <span class="n">destY</span><span class="p">);</span>
<span class="p">}</span>
<span class="k">if</span> <span class="p">(</span><span class="n">isPressed</span><span class="p">(</span><span class="n">BUTTON_DOWN</span><span class="p">))</span> <span class="p">{</span>
<span class="c1">// Move the unit down one.</span>
<span class="kt">int</span> <span class="n">destY</span> <span class="o">=</span> <span class="n">unit</span><span class="o">-></span><span class="n">y</span><span class="p">()</span> <span class="o">+</span> <span class="mi">1</span><span class="p">;</span>
<span class="k">return</span> <span class="k">new</span> <span class="n">MoveUnitCommand</span><span class="p">(</span><span class="n">unit</span><span class="p">,</span> <span class="n">unit</span><span class="o">-></span><span class="n">x</span><span class="p">(),</span> <span class="n">destY</span><span class="p">);</span>
<span class="p">}</span>
<span class="c1">// Other moves...</span>
<span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div>
<aside name="free">
<p>Of course, in a non-garbage-collected language like C++, this means the code
executing commands will also be responsible for freeing their memory.</p>
</aside>
<p>The fact that commands are one-use-only will come to our advantage in a second.
To make commands undoable, we define another operation each command class needs
to implement:</p>
<div class="codehilite"><pre><span></span><code><span class="k">class</span> <span class="nc">Command</span>
<span class="p">{</span>
<span class="k">public</span><span class="o">:</span>
<span class="k">virtual</span> <span class="o">~</span><span class="n">Command</span><span class="p">()</span> <span class="p">{}</span>
<span class="k">virtual</span> <span class="kt">void</span> <span class="n">execute</span><span class="p">()</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
<span class="k">virtual</span> <span class="kt">void</span> <span class="nf">undo</span><span class="p">()</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">};</span>
</code></pre></div>
<p>An <code>undo()</code> method reverses the game state changed by the corresponding
<code>execute()</code> method. Here’s our previous move command with undo support:</p>
<div class="codehilite"><pre><span></span><code><span class="k">class</span> <span class="nc">MoveUnitCommand</span> <span class="o">:</span> <span class="k">public</span> <span class="n">Command</span>
<span class="p">{</span>
<span class="k">public</span><span class="o">:</span>
<span class="n">MoveUnitCommand</span><span class="p">(</span><span class="n">Unit</span><span class="o">*</span> <span class="n">unit</span><span class="p">,</span> <span class="kt">int</span> <span class="n">x</span><span class="p">,</span> <span class="kt">int</span> <span class="n">y</span><span class="p">)</span>
<span class="o">:</span> <span class="n">unit_</span><span class="p">(</span><span class="n">unit</span><span class="p">),</span>
<span class="n">xBefore_</span><span class="p">(</span><span class="mi">0</span><span class="p">),</span>
<span class="n">yBefore_</span><span class="p">(</span><span class="mi">0</span><span class="p">),</span>
<span class="n">x_</span><span class="p">(</span><span class="n">x</span><span class="p">),</span>
<span class="n">y_</span><span class="p">(</span><span class="n">y</span><span class="p">)</span>
<span class="p">{}</span>
<span class="k">virtual</span> <span class="kt">void</span> <span class="n">execute</span><span class="p">()</span>
<span class="p">{</span>
<span class="c1">// Remember the unit's position before the move</span>
<span class="c1">// so we can restore it.</span>
<span class="n">xBefore_</span> <span class="o">=</span> <span class="n">unit_</span><span class="o">-></span><span class="n">x</span><span class="p">();</span>
<span class="n">yBefore_</span> <span class="o">=</span> <span class="n">unit_</span><span class="o">-></span><span class="n">y</span><span class="p">();</span>
<span class="n">unit_</span><span class="o">-></span><span class="n">moveTo</span><span class="p">(</span><span class="n">x_</span><span class="p">,</span> <span class="n">y_</span><span class="p">);</span>
<span class="p">}</span>
<span class="k">virtual</span> <span class="kt">void</span> <span class="n">undo</span><span class="p">()</span>
<span class="p">{</span>
<span class="n">unit_</span><span class="o">-></span><span class="n">moveTo</span><span class="p">(</span><span class="n">xBefore_</span><span class="p">,</span> <span class="n">yBefore_</span><span class="p">);</span>
<span class="p">}</span>
<span class="k">private</span><span class="o">:</span>
<span class="n">Unit</span><span class="o">*</span> <span class="n">unit_</span><span class="p">;</span>
<span class="kt">int</span> <span class="n">xBefore_</span><span class="p">,</span> <span class="n">yBefore_</span><span class="p">;</span>
<span class="kt">int</span> <span class="n">x_</span><span class="p">,</span> <span class="n">y_</span><span class="p">;</span>
<span class="p">};</span>
</code></pre></div>
<p>Note that we added some <span name="memento">more state</span> to the class.
When a unit moves, it forgets where it used to be. If we want to be able to undo
that move, we have to remember the unit’s previous position ourselves, which is
what <code>xBefore_</code> and <code>yBefore_</code> do.</p>
<aside name="memento">
<p>This seems like a place for the <a
href="http://en.wikipedia.org/wiki/Memento_pattern"
class="gof-pattern">Memento</a> pattern, but I haven’t found it to work well.
Since commands tend to modify only a small part of an object’s state,
snapshotting the rest of its data is a waste of memory. It’s cheaper to
manually store only the bits you change.</p>
<p><a href="http://en.wikipedia.org/wiki/Persistent_data_structure"><em>Persistent
data structures</em></a> are another option. With these, every modification to an
object returns a new one, leaving the original unchanged. Through clever
implementation, these new objects share data with the previous ones, so it’s
much cheaper than cloning the entire object.</p>
<p>Using a persistent data structure, each command stores a reference to the
object before the command was performed, and undo just means switching back to
the old object.</p>
</aside>
<p>To let the player undo a move, we keep around the last command they executed.
When they bang on Control-Z, we call that command’s <code>undo()</code> method. (If they’ve
already undone, then it becomes “redo” and we execute the command again.)</p>
<p>Supporting multiple levels of undo isn’t much harder. Instead of remembering the
last command, we keep a list of commands and a reference to the “current” one.
When the player executes a command, we append it to the list and point “current”
at it.</p>
<p><img src="images/command-undo.png" alt="A stack of commands from older to newer. A 'current' arrow points to one command, an 'undo' arrow points to the previous one, and 'redo' points to the next." /></p>
<p>When the player chooses “Undo”, we undo the current command and move the current
pointer back. When they choose <span name="replay">“Redo”</span>, we advance the
pointer
and then execute that command. If they choose a new command after undoing some,
everything in the list after the current command is discarded.</p>
<p>The first time I implemented this in a level editor, I felt like a genius. I was
astonished at how straightforward it was and how well it worked. It takes
discipline to make sure every data modification goes through a command, but once
you do that, the rest is easy.</p>
<aside name="replay">
<p>Redo may not be common in games, but re-<em>play</em> is. A naïve implementation would
record the entire game state at each frame so it can be replayed, but that would
use too much memory.</p>
<p>Instead, many games record the set of commands every entity performed each
frame. To replay the game, the engine just runs the normal game simulation,
executing the pre-recorded commands.</p>
</aside>
<h2><a href="#classy-and-dysfunctional" name="classy-and-dysfunctional">Classy and Dysfunctional?</a></h2>
<p>Earlier, I said commands are similar to first-class functions or closures, but
every example I showed here used class definitions. If you’re familiar with
functional programming, you’re probably wondering where the functions are.</p>
<p>I wrote the examples this way because C++ has pretty limited support for
first-class functions. Function pointers are stateless, functors are weird and
still
require defining a class, and the lambdas in C++11 are tricky to work with
because of manual memory management.</p>
<p>That’s <em>not</em> to say you shouldn’t use functions for the Command pattern in other
languages. If you have the luxury of a language with real closures, by all means,
use them! In <span name="some">some</span> ways, the Command pattern is a way of
emulating closures in languages that don’t have them.</p>
<aside name="some">
<p>I say <em>some</em> ways here because building actual classes or structures for
commands is still useful even in languages that have closures. If your command
has multiple operations (like undoable commands), mapping that to a single
function is awkward.</p>
<p>Defining an actual class with fields also helps readers easily tell what data
the command contains. Closures are a wonderfully terse way of automatically
wrapping up some state, but they can be so automatic that it’s hard to see what
state they’re actually holding.</p>
</aside>
<p>For example, if we were building a game in JavaScript, we could create a move
unit command just like this:</p>
<div class="codehilite"><pre><span></span><code><span class="kd">function</span> <span class="nx">makeMoveUnitCommand</span><span class="p">(</span><span class="nx">unit</span><span class="p">,</span> <span class="nx">x</span><span class="p">,</span> <span class="nx">y</span><span class="p">)</span> <span class="p">{</span>
<span class="c1">// This function here is the command object:</span>
<span class="k">return</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
<span class="nx">unit</span><span class="p">.</span><span class="nx">moveTo</span><span class="p">(</span><span class="nx">x</span><span class="p">,</span> <span class="nx">y</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">}</span>
</code></pre></div>
<p>We could add support for undo as well using a pair of closures:</p>
<div class="codehilite"><pre><span></span><code><span class="kd">function</span> <span class="nx">makeMoveUnitCommand</span><span class="p">(</span><span class="nx">unit</span><span class="p">,</span> <span class="nx">x</span><span class="p">,</span> <span class="nx">y</span><span class="p">)</span> <span class="p">{</span>
<span class="kd">var</span> <span class="nx">xBefore</span><span class="p">,</span> <span class="nx">yBefore</span><span class="p">;</span>
<span class="k">return</span> <span class="p">{</span>
<span class="nx">execute</span><span class="o">:</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
<span class="nx">xBefore</span> <span class="o">=</span> <span class="nx">unit</span><span class="p">.</span><span class="nx">x</span><span class="p">();</span>
<span class="nx">yBefore</span> <span class="o">=</span> <span class="nx">unit</span><span class="p">.</span><span class="nx">y</span><span class="p">();</span>
<span class="nx">unit</span><span class="p">.</span><span class="nx">moveTo</span><span class="p">(</span><span class="nx">x</span><span class="p">,</span> <span class="nx">y</span><span class="p">);</span>
<span class="p">},</span>
<span class="nx">undo</span><span class="o">:</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
<span class="nx">unit</span><span class="p">.</span><span class="nx">moveTo</span><span class="p">(</span><span class="nx">xBefore</span><span class="p">,</span> <span class="nx">yBefore</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">};</span>
<span class="p">}</span>
</code></pre></div>
<p>If you’re comfortable with a functional style, this way of doing things is
natural. If you aren’t, I hope this chapter helped you along the way a bit. For
me, the usefulness of the Command pattern really shows how effective the
functional paradigm is for many problems.</p>
<h2><a href="#see-also" name="see-also">See Also</a></h2>
<ul>
<li>
<p>You may end up with a lot of different command classes. In order to make it
easier to implement those, it’s often helpful to define a concrete base
class with a bunch of convenient high-level methods that the derived
commands can compose to define their behavior. That turns the command’s main
<code>execute()</code> method into a <a href="subclass-sandbox.html"
class="pattern">Subclass Sandbox</a>.</p>
</li>
<li>
<p>In our examples, we explicitly chose which actor would handle a command. In
some cases, especially where your object model is hierarchical, it may not
be so cut-and-dried. An object may respond to a command, or it may decide to
pawn it off on some subordinate object. If you do that, you’ve got yourself
a <a class="gof-pattern" href="
http://en.wikipedia.org/wiki/Chain-of-responsibility_pattern">Chain of Responsibility</a>.</p>
</li>
<li>
<p>Some commands are stateless chunks of pure behavior like the <code>JumpCommand</code>
in the first example. In cases like that, having <span
name="singleton">more</span> than one instance of that class wastes memory
since all instances are equivalent. The <a class="gof-pattern"
href="flyweight.html">Flyweight</a> pattern addresses that.</p>
<aside name="singleton">
<p>You could make it a <a href="singleton.html" class="gof-
pattern">Singleton</a> too, but friends don’t let friends create singletons.</p>
</aside>
</li>
</ul>
<nav>
<span class="prev">← <a href="design-patterns-revisited.html">Previous Chapter</a></span>
<span class="next"><a href="flyweight.html">Next Chapter</a> →</span>
<span class="toc">≡ <a href="/">The Book</a></span>
</nav>
</div>
</div>
<footer>© 2009-2021 Robert Nystrom</footer>
</body>
</html>