forked from munificent/game-programming-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice-locator.html
More file actions
760 lines (696 loc) · 45.1 KB
/
Copy pathservice-locator.html
File metadata and controls
760 lines (696 loc) · 45.1 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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
<!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>Service Locator · Decoupling Patterns · 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="http://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-1.10.1.min.js"></script>
<script src="script.js"></script>
</head>
<body id="top">
<div class="page sidebar">
<div class="content">
<nav class="top">
<span class="prev">← <a href="event-queue.html">Previous Chapter</a></span>
<span class="next"><a href="optimization-patterns.html">Next Chapter</a> →</span>
<span class="toc">≡ <a href="/">The Book</a></span>
</nav>
<h1>Service Locator</h1>
<h1 class="book"><a href="/">Game Programming Patterns</a><span class="section"><a href="decoupling-patterns.html">Decoupling Patterns</a></span></h1>
<h2><a href="#intent" name="intent">Intent</a></h2>
<p><em>Provide a global point of access to a service without coupling users to the
concrete class that implements it.</em></p>
<h2><a href="#motivation" name="motivation">Motivation</a></h2>
<p>Some objects or systems in a game tend to get around, visiting almost every
corner of the codebase. It’s hard to find a part of the game that <em>won’t</em> need a
memory allocator, logging, or random numbers at some point.
Systems like those can be thought of as <em>services</em> that need to be available to
the entire game.</p>
<p>For our example, we’ll consider audio. It doesn’t have quite the reach of
something lower-level like a memory allocator, but it still touches a bunch of
game systems. A falling rock hits the ground with a crash (physics). A sniper
NPC fires his rifle and a shot rings out (AI). The user selects a menu item with
a beep of confirmation (user interface).</p>
<p>Each of these places will need to be able to call into the audio system with
something like one of these:</p>
<div class="codehilite"><pre><span class="c1">// Use a static class?</span>
<span class="n">AudioSystem</span><span class="o">::</span><span class="n">playSound</span><span class="p">(</span><span class="n">VERY_LOUD_BANG</span><span class="p">);</span>
<span class="c1">// Or maybe a singleton?</span>
<span class="n">AudioSystem</span><span class="o">::</span><span class="n">instance</span><span class="p">()</span><span class="o">-></span><span class="n">playSound</span><span class="p">(</span><span class="n">VERY_LOUD_BANG</span><span class="p">);</span>
</pre></div>
<p>Either gets us where we’re trying to go, but we stumbled into some sticky
coupling along the way. Every place in the game calling into our audio system
directly references the concrete <code>AudioSystem</code> class and the mechanism for
accessing it — either as a static class or a <a class="gof-pattern"
href="singleton.html">singleton</a>.</p>
<p>These call sites, of course, have to be coupled to <em>something</em> in order to make a
sound play, but letting them poke at the concrete audio implementation directly
is like giving a hundred strangers directions to your house just so they can
drop a letter on your doorstep. Not only is it a little bit <em>too</em> personal, it’s
a real pain when you move and you have to tell each person the new directions.</p>
<p>There’s a better solution: a phone book. People that need to get in touch with
us can look us up by name and get our current address. When we move, we tell the
phone company. They update the book, and everyone gets the new address. In fact,
we don’t even need to give out our real address at all. We can list a P.O. box
or some other “representation” of ourselves instead. By having callers go
through the book to find us, we have <em>a convenient single place where we control
how we’re found.</em></p>
<p>This is the Service Locator pattern in a nutshell — it decouples code that needs
a service from both <em>who</em> it is (the concrete implementation type) and <em>where</em>
it is (how we get to the instance of it).</p>
<h2><a href="#the-pattern" name="the-pattern">The Pattern</a></h2>
<p>A <strong>service</strong> class defines an abstract interface to a set of operations. A
concrete <strong>service provider</strong> implements this interface. A separate <strong>service
locator</strong> provides access to the service by finding an appropriate provider
while hiding both the provider’s concrete type and the process used to locate
it.</p>
<h2><a href="#when-to-use-it" name="when-to-use-it">When to Use It</a></h2>
<p>Anytime you make something accessible to every part of your program,
you’re asking for trouble. That’s the main problem with the <a
class="gof-pattern" href="singleton.html">Singleton</a> pattern, and this
pattern is no different. My simplest advice for when to use a service locator
is: <em>sparingly</em>.</p>
<p>Instead of using a global mechanism to give some code access to an object it
needs, first consider <em>passing the object to it instead</em>. That’s dead simple, and
it makes the coupling completely obvious. That will cover most of your needs.</p>
<p><em>But…</em> there are some times when manually passing around an object is
gratuitous or actively makes code harder to read. Some systems, like logging or
memory management, shouldn’t be part of a module’s public API. The parameters to
your rendering code should have to do with <em>rendering</em>, not stuff like logging.</p>
<p>Likewise, other systems represent facilities that are fundamentally singular in
nature. Your game probably only has one audio device or display system that it
can talk to. It is an ambient property of the environment, so plumbing it
through ten layers of methods just so one deeply nested call can get to it is
adding needless complexity to your code.</p>
<p>In those kinds of cases, this pattern can help. As we’ll see, it functions as a
more flexible, more configurable cousin of the Singleton pattern. When used <span
name="well">well</span>, it can make your codebase more flexible with little
runtime cost.</p>
<aside name="well">
<p>Conversely, when used poorly, it carries with it all of the baggage of the
Singleton pattern with worse runtime performance.</p>
</aside>
<h2><a href="#keep-in-mind" name="keep-in-mind">Keep in Mind</a></h2>
<p>The core difficulty with a service locator is that it takes a dependency — a
bit of coupling between two pieces of code — and defers wiring it up until
runtime. This gives you flexibility, but the price you pay is that it’s harder
to understand what your dependencies are by reading the code.</p>
<h3><a href="#the-service-actually-has-to-be-located" name="the-service-actually-has-to-be-located">The service actually has to be located</a></h3>
<p>With a singleton or a static class, there’s no chance for the instance we need
to <em>not</em> be available. Calling code can take for granted that it’s there. But
since this pattern has to <em>locate</em> the service, we may need to handle cases
where that fails. Fortunately, we’ll cover a strategy later to address this and
guarantee that we’ll always get <em>some</em> service when you need it.</p>
<h3><a href="#the-service-doesn't-know-who-is-locating-it" name="the-service-doesn't-know-who-is-locating-it">The service doesn’t know who is locating it</a></h3>
<p>Since the locator is globally accessible, any code in the game could be
requesting a service and then poking at it. This means that the service must be able
to work correctly in any circumstance. For example, a class that expects to
be used only during the simulation portion of the game loop and not during rendering
may not work as a service — it wouldn’t be able to ensure that it’s being used
at the right time. So, if a class expects to be used only in a certain context,
it’s safest to avoid exposing it to the entire world with this pattern.</p>
<h2><a href="#sample-code" name="sample-code">Sample Code</a></h2>
<p>Getting back to our audio system problem, let’s address it by exposing the
system to the rest of the codebase through a service locator.</p>
<h3><a href="#the-service" name="the-service">The service</a></h3>
<p>We’ll start off with the audio API. This is the interface that our service will
be exposing:</p>
<div class="codehilite"><pre><span class="k">class</span> <span class="nc">Audio</span>
<span class="p">{</span>
<span class="nl">public:</span>
<span class="k">virtual</span> <span class="o">~</span><span class="n">Audio</span><span class="p">()</span> <span class="p">{}</span>
<span class="k">virtual</span> <span class="kt">void</span> <span class="n">playSound</span><span class="p">(</span><span class="kt">int</span> <span class="n">soundID</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="n">stopSound</span><span class="p">(</span><span class="kt">int</span> <span class="n">soundID</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="n">stopAllSounds</span><span class="p">()</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">};</span>
</pre></div>
<p>A real audio engine would be much more complex than this, of course, but this
shows the basic idea. What’s important is that it’s an abstract interface class
with no implementation bound to it.</p>
<h3><a href="#the-service-provider" name="the-service-provider">The service provider</a></h3>
<p>By itself, our audio interface isn’t very useful. We need a concrete
implementation. This book isn’t about how to write audio code for a game
console, so you’ll have to imagine there’s some actual code in the bodies of
these functions, but you get the idea:</p>
<div class="codehilite"><pre><span class="k">class</span> <span class="nc">ConsoleAudio</span> <span class="o">:</span> <span class="k">public</span> <span class="n">Audio</span>
<span class="p">{</span>
<span class="nl">public:</span>
<span class="k">virtual</span> <span class="kt">void</span> <span class="n">playSound</span><span class="p">(</span><span class="kt">int</span> <span class="n">soundID</span><span class="p">)</span>
<span class="p">{</span>
<span class="c1">// Play sound using console audio api...</span>
<span class="p">}</span>
<span class="k">virtual</span> <span class="kt">void</span> <span class="n">stopSound</span><span class="p">(</span><span class="kt">int</span> <span class="n">soundID</span><span class="p">)</span>
<span class="p">{</span>
<span class="c1">// Stop sound using console audio api...</span>
<span class="p">}</span>
<span class="k">virtual</span> <span class="kt">void</span> <span class="n">stopAllSounds</span><span class="p">()</span>
<span class="p">{</span>
<span class="c1">// Stop all sounds using console audio api...</span>
<span class="p">}</span>
<span class="p">};</span>
</pre></div>
<p>Now we have an interface and an implementation. The remaining piece is the
service locator — the class that ties the two together.</p>
<h3><a href="#a-simple-locator" name="a-simple-locator">A simple locator</a></h3>
<p>The implementation here is about the simplest kind of service locator you can
define:</p>
<p><span name="di"></span></p>
<div class="codehilite"><pre><span class="k">class</span> <span class="nc">Locator</span>
<span class="p">{</span>
<span class="nl">public:</span>
<span class="k">static</span> <span class="n">Audio</span><span class="o">*</span> <span class="n">getAudio</span><span class="p">()</span> <span class="p">{</span> <span class="k">return</span> <span class="n">service_</span><span class="p">;</span> <span class="p">}</span>
<span class="k">static</span> <span class="kt">void</span> <span class="n">provide</span><span class="p">(</span><span class="n">Audio</span><span class="o">*</span> <span class="n">service</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">service_</span> <span class="o">=</span> <span class="n">service</span><span class="p">;</span>
<span class="p">}</span>
<span class="nl">private:</span>
<span class="k">static</span> <span class="n">Audio</span><span class="o">*</span> <span class="n">service_</span><span class="p">;</span>
<span class="p">};</span>
</pre></div>
<aside name="di">
<p>The technique this uses is called <em>dependency injection</em>, an awkward bit of
jargon for a very simple idea. Say you have one class that depends on another.
In our case, our <code>Locator</code> class needs an instance of the <code>Audio</code> service.
Normally, the locator would be responsible for constructing that instance itself.
Dependency injection instead says that outside code is responsible for
<em>injecting</em> that dependency into the object that needs it.</p>
</aside>
<p>The static <code>getAudio()</code> function does the locating. We can call it from
anywhere in the codebase, and it will give us back an instance of our <code>Audio</code>
service to use:</p>
<div class="codehilite"><pre><span class="n">Audio</span> <span class="o">*</span><span class="n">audio</span> <span class="o">=</span> <span class="n">Locator</span><span class="o">::</span><span class="n">getAudio</span><span class="p">();</span>
<span class="n">audio</span><span class="o">-></span><span class="n">playSound</span><span class="p">(</span><span class="n">VERY_LOUD_BANG</span><span class="p">);</span>
</pre></div>
<p>The way it “locates” is very simple — it relies on some outside code to register
a service provider before anything tries to use the service. When the game is
starting up, it calls some code like this:</p>
<div class="codehilite"><pre><span class="n">ConsoleAudio</span> <span class="o">*</span><span class="n">audio</span> <span class="o">=</span> <span class="k">new</span> <span class="n">ConsoleAudio</span><span class="p">();</span>
<span class="n">Locator</span><span class="o">::</span><span class="n">provide</span><span class="p">(</span><span class="n">audio</span><span class="p">);</span>
</pre></div>
<p>The key part to notice here is that the code that calls <code>playSound()</code> isn’t aware of
the concrete <code>ConsoleAudio</code> class; it only knows the abstract <code>Audio</code> interface. Equally
important, not even the <em>locator</em> class is coupled to the concrete service
provider. The <em>only</em> place in code that knows about the actual concrete class is
the initialization code that provides the service.</p>
<p>There’s one more level of decoupling here: the <code>Audio</code> interface isn’t aware of
the fact that it’s being accessed in most places through a service locator. As
far as it knows, it’s just a regular abstract base class. This is useful because
it means we can apply this pattern to <em>existing</em> classes that weren’t
necessarily designed around it. This is in contrast with <a class="gof-pattern"
href="singleton.html">Singleton</a>, which affects the design of the “service”
class itself.</p>
<h3><a href="#a-null-service" name="a-null-service">A null service</a></h3>
<p>Our implementation so far is certainly simple, and it’s pretty flexible too. But
it has one big shortcoming: if we try to use the service <span
name="temporal">before</span> a provider has been registered, it returns <code>NULL</code>.
If the calling code doesn’t check that, we’re going to crash the game.</p>
<aside name="temporal">
<p>I sometimes hear this called “temporal coupling” — two separate pieces of code
that must be called in the right order for the program to work correctly. All
stateful software has some degree of this, but as with other kinds of coupling,
reducing temporal coupling makes the codebase easier to manage.</p>
</aside>
<p>Fortunately, there’s another design pattern called “Null Object” that we can use
to address this. The basic idea is that in places where we would return <code>NULL</code>
when we fail to find or create an object, we instead return a special object
that implements the same interface as the desired object. Its implementation
basically does nothing, but it allows code that receives the object to safely
continue on as if it had received a “real” one.</p>
<p>To use this, we’ll define another “null” service provider:</p>
<div class="codehilite"><pre><span class="k">class</span> <span class="nc">NullAudio</span><span class="o">:</span> <span class="k">public</span> <span class="n">Audio</span>
<span class="p">{</span>
<span class="nl">public:</span>
<span class="k">virtual</span> <span class="kt">void</span> <span class="n">playSound</span><span class="p">(</span><span class="kt">int</span> <span class="n">soundID</span><span class="p">)</span> <span class="p">{</span> <span class="cm">/* Do nothing. */</span> <span class="p">}</span>
<span class="k">virtual</span> <span class="kt">void</span> <span class="n">stopSound</span><span class="p">(</span><span class="kt">int</span> <span class="n">soundID</span><span class="p">)</span> <span class="p">{</span> <span class="cm">/* Do nothing. */</span> <span class="p">}</span>
<span class="k">virtual</span> <span class="kt">void</span> <span class="n">stopAllSounds</span><span class="p">()</span> <span class="p">{</span> <span class="cm">/* Do nothing. */</span> <span class="p">}</span>
<span class="p">};</span>
</pre></div>
<p>As you can see, it implements the service interface, but doesn’t actually do
anything. Now, we change our locator to this:</p>
<p><span name="ref"></span></p>
<div class="codehilite"><pre><span class="k">class</span> <span class="nc">Locator</span>
<span class="p">{</span>
<span class="nl">public:</span>
<span class="k">static</span> <span class="kt">void</span> <span class="n">initialize</span><span class="p">()</span> <span class="p">{</span> <span class="n">service_</span> <span class="o">=</span> <span class="o">&</span><span class="n">nullService_</span><span class="p">;</span> <span class="p">}</span>
<span class="k">static</span> <span class="n">Audio</span><span class="o">&</span> <span class="n">getAudio</span><span class="p">()</span> <span class="p">{</span> <span class="k">return</span> <span class="o">*</span><span class="n">service_</span><span class="p">;</span> <span class="p">}</span>
<span class="k">static</span> <span class="kt">void</span> <span class="n">provide</span><span class="p">(</span><span class="n">Audio</span><span class="o">*</span> <span class="n">service</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="n">service</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span>
<span class="p">{</span>
<span class="c1">// Revert to null service.</span>
<span class="n">service_</span> <span class="o">=</span> <span class="o">&</span><span class="n">nullService_</span><span class="p">;</span>
<span class="p">}</span>
<span class="k">else</span>
<span class="p">{</span>
<span class="n">service_</span> <span class="o">=</span> <span class="n">service</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="nl">private:</span>
<span class="k">static</span> <span class="n">Audio</span><span class="o">*</span> <span class="n">service_</span><span class="p">;</span>
<span class="k">static</span> <span class="n">NullAudio</span> <span class="n">nullService_</span><span class="p">;</span>
<span class="p">};</span>
</pre></div>
<aside name="ref">
<p>You may notice we’re returning the service by reference instead of by pointer
now. Since references in C++ are (in theory!) never <code>NULL</code>, returning a
reference is a hint to users of the code that they can expect to always get a
valid object back.</p>
<p>The other thing to notice is that we’re checking for <code>NULL</code> in the <code>provide()</code>
function instead of checking for the accessor. That requires us to call <code>initialize()</code> early
on to make sure that the locator initially correctly defaults to the null
provider. In return, it moves the branch out of <code>getAudio()</code>, which will save us
a couple of cycles every time the service is accessed.</p>
</aside>
<p>Calling code will never know that a “real” service wasn’t found, nor does it
have to worry about handling <code>NULL</code>. It’s guaranteed to always get back a valid
object.</p>
<p>This is also useful for <em>intentionally</em> failing to find services. If we want to
<span name="disable">disable</span> a system temporarily, we now have an easy
way to do so: simply don’t register a provider for the service, and the locator
will default to a null provider.</p>
<aside name="disable">
<p>Turning off audio is handy during development. It frees up some memory and CPU
cycles. More importantly, when you break into a debugger just as a loud sound
starts playing, it saves you from having your eardrums shredded. There’s nothing
like twenty milliseconds of a scream sound effect looping at full volume to get
your blood flowing in the morning.</p>
</aside>
<h3><a href="#logging-decorator" name="logging-decorator">Logging decorator</a></h3>
<p>Now that our system is pretty robust, let’s discuss another refinement this
pattern lets us do — decorated services. I’ll explain with an example.</p>
<p>During development, a little logging when interesting events occur can help you
figure out what’s going on under the hood of your game engine. If you’re working
on AI, you’d like to know when an entity changes AI states. If you’re the sound
programmer, you may want a record of every sound as it plays so you can check
that they trigger in the right order.</p>
<p>The typical solution is to litter the code with calls to some <code>log()</code>
function. Unfortunately, that replaces one problem with another — now we have
<em>too much</em> logging. The AI coder doesn’t care when sounds are playing,
and the sound person doesn’t care about AI state transitions, but now they both
have to wade through each other’s messages.</p>
<p>Ideally, we would be able to selectively enable logging for just the stuff we
care about, and in the final game build, there’d be no logging at all. If the
different systems we want to conditionally log are exposed as services, then we
can solve this using the <a class="gof-pattern"
href="http://www.c2.com/cgi/wiki?DecoratorPattern">Decorator</a> pattern. Let’s
define another audio service provider implementation like this:</p>
<div class="codehilite"><pre><span class="k">class</span> <span class="nc">LoggedAudio</span> <span class="o">:</span> <span class="k">public</span> <span class="n">Audio</span>
<span class="p">{</span>
<span class="nl">public:</span>
<span class="n">LoggedAudio</span><span class="p">(</span><span class="n">Audio</span> <span class="o">&</span><span class="n">wrapped</span><span class="p">)</span>
<span class="o">:</span> <span class="n">wrapped_</span><span class="p">(</span><span class="n">wrapped</span><span class="p">)</span>
<span class="p">{}</span>
<span class="k">virtual</span> <span class="kt">void</span> <span class="n">playSound</span><span class="p">(</span><span class="kt">int</span> <span class="n">soundID</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">log</span><span class="p">(</span><span class="s">"play sound"</span><span class="p">);</span>
<span class="n">wrapped_</span><span class="p">.</span><span class="n">playSound</span><span class="p">(</span><span class="n">soundID</span><span class="p">);</span>
<span class="p">}</span>
<span class="k">virtual</span> <span class="kt">void</span> <span class="n">stopSound</span><span class="p">(</span><span class="kt">int</span> <span class="n">soundID</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">log</span><span class="p">(</span><span class="s">"stop sound"</span><span class="p">);</span>
<span class="n">wrapped_</span><span class="p">.</span><span class="n">stopSound</span><span class="p">(</span><span class="n">soundID</span><span class="p">);</span>
<span class="p">}</span>
<span class="k">virtual</span> <span class="kt">void</span> <span class="n">stopAllSounds</span><span class="p">()</span>
<span class="p">{</span>
<span class="n">log</span><span class="p">(</span><span class="s">"stop all sounds"</span><span class="p">);</span>
<span class="n">wrapped_</span><span class="p">.</span><span class="n">stopAllSounds</span><span class="p">();</span>
<span class="p">}</span>
<span class="nl">private:</span>
<span class="kt">void</span> <span class="n">log</span><span class="p">(</span><span class="k">const</span> <span class="kt">char</span><span class="o">*</span> <span class="n">message</span><span class="p">)</span>
<span class="p">{</span>
<span class="c1">// Code to log message...</span>
<span class="p">}</span>
<span class="n">Audio</span> <span class="o">&</span><span class="n">wrapped_</span><span class="p">;</span>
<span class="p">};</span>
</pre></div>
<p>As you can see, it wraps another audio provider and exposes the same interface.
It forwards the actual audio behavior to the inner provider, but it also logs each
sound call. If a programmer wants to enable audio logging, they call this:</p>
<div class="codehilite"><pre><span class="kt">void</span> <span class="nf">enableAudioLogging</span><span class="p">()</span>
<span class="p">{</span>
<span class="c1">// Decorate the existing service.</span>
<span class="n">Audio</span> <span class="o">*</span><span class="n">service</span> <span class="o">=</span> <span class="k">new</span> <span class="n">LoggedAudio</span><span class="p">(</span><span class="n">Locator</span><span class="o">::</span><span class="n">getAudio</span><span class="p">());</span>
<span class="c1">// Swap it in.</span>
<span class="n">Locator</span><span class="o">::</span><span class="n">provide</span><span class="p">(</span><span class="n">service</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
<p>Now, any calls to the audio service will be logged before continuing as before.
And, of course, this plays nicely with our null service, so you can both
<em>disable</em> audio and yet still log the sounds that it <em>would</em> play if sound were
enabled.</p>
<h2><a href="#design-decisions" name="design-decisions">Design Decisions</a></h2>
<p>We’ve covered a typical implementation, but there are a couple of ways that it can
vary based on differing answers to a few core questions:</p>
<h3><a href="#how-is-the-service-located" name="how-is-the-service-located">How is the service located?</a></h3>
<ul>
<li>
<p><strong>Outside code registers it:</strong></p>
<p>This is the mechanism our sample code uses to locate the service, and it’s the
most common design I see in games:</p>
<ul>
<li>
<p><em>It’s fast and simple.</em> The <code>getAudio()</code> function simply returns a
pointer. It will often get inlined by the compiler, so we get a nice
abstraction layer at almost no performance cost.</p>
</li>
<li>
<p><em>We control how the provider is constructed.</em> Consider a service for
accessing the game’s controllers. We have two concrete providers: one
for regular games and one for playing online. The online provider passes
controller input over the network so that, to the rest of the game,
remote players appear to be using local controllers.</p>
<p>To make this work, the online concrete provider needs to know the IP
address of the other remote player. If the locator itself was
constructing the object, how would it know what to pass in? The <code>Locator</code>
class doesn’t know anything about online at all, much less some other
user’s IP address.</p>
<p>Externally registered providers dodge the problem. Instead of the
locator constructing the class, the game’s networking code instantiates
the online-specific service provider, passing in the IP address it
needs. Then it gives that to the locator, who knows only about the
service’s abstract interface.</p>
</li>
<li>
<p><em>We can change the service while the game is running.</em> We may not use
this in the final game, but it’s a neat trick during development. While
testing, we can swap out, for example, the audio service with the null
service we talked about earlier to temporarily disable sound while the
game is still running.</p>
</li>
<li>
<p><em>The locator depends on outside code.</em> This is the downside. Any code
accessing the service presumes that some code somewhere has already
registered it. If that initialization doesn’t happen, we’ll either crash
or have a service mysteriously not working.</p>
</li>
</ul>
</li>
<li>
<p><strong>Bind to it at compile time:</strong></p>
<p>The idea here is that the “location” process actually occurs at compile time
using preprocessor macros. Like so:</p>
<div class="codehilite"><pre><span class="k">class</span> <span class="nc">Locator</span>
<span class="p">{</span>
<span class="nl">public:</span>
<span class="k">static</span> <span class="n">Audio</span><span class="o">&</span> <span class="n">getAudio</span><span class="p">()</span> <span class="p">{</span> <span class="k">return</span> <span class="n">service_</span><span class="p">;</span> <span class="p">}</span>
<span class="nl">private:</span>
<span class="err">#</span><span class="k">if</span> <span class="n">DEBUG</span>
<span class="k">static</span> <span class="n">DebugAudio</span> <span class="n">service_</span><span class="p">;</span>
<span class="err">#</span><span class="k">else</span>
<span class="k">static</span> <span class="n">ReleaseAudio</span> <span class="n">service_</span><span class="p">;</span>
<span class="err">#</span><span class="n">endif</span>
<span class="p">};</span>
</pre></div>
<p>Locating the service like this implies a few things:</p>
<ul>
<li>
<p><em>It’s fast.</em> Since all of the real work is done at compile time, there’s
nothing left to do at runtime. The compiler will likely inline the
<code>getAudio()</code> call, giving us a solution that’s as fast as we could hope
for.</p>
</li>
<li>
<p><em>You can guarantee the service is available.</em> Since the locator owns the
service now and selects it at compile time, we can be assured that if
the game compiles, we won’t have to worry about the service being
unavailable.</p>
</li>
<li>
<p><em>You can’t change the service easily.</em> This is the major downside. Since
the binding happens at build time, anytime you want to change the
service, you’ve got to recompile and restart the game.</p>
</li>
</ul>
</li>
<li>
<p><strong>Configure it at runtime:</strong></p>
<p>Over in the khaki-clad land of enterprise business software, if you say
“service locator”, this is what they’ll have in mind. When the service is
requested, the locator does some <span name="reflection">magic</span> at
runtime to hunt down the actual implementation requested.</p>
<aside name="reflection">
<p><em>Reflection</em> is a capability of some programming languages to interact with
the type system at runtime. For example, we could find a class with a given
name, find its constructor, and then invoke it to create an instance.</p>
<p>Dynamically typed languages like Lisp, Smalltalk, and Python get this by
their very nature, but newer static languages like C# and Java also support
it.</p>
</aside>
<p>Typically, this means loading a configuration file that identifies the
provider and then using reflection to instantiate that class at runtime. This
does a few things for us:</p>
<ul>
<li>
<p><em>We can swap out the service without recompiling.</em> This is a little more
flexible than a compile-time-bound service, but not quite as flexible as
a registered one where you can actually change the service while the
game is running.</p>
</li>
<li>
<p><em>Non-programmers can change the service.</em> This is nice for when the
designers want to be able to turn certain game features on and off but
aren’t comfortable mucking through source code. (Or, more likely, the
<em>coders</em> aren’t comfortable with them mucking through it.)</p>
</li>
<li>
<p><em>The same codebase can support multiple configurations simultaneously.</em>
Since the location process has been moved out of the codebase entirely,
we can use the same code to support multiple service configurations
simultaneously.</p>
<p>This is one of the reasons this model is appealing over in enterprise
web-land: you can deploy a single app that works on different server
setups just by changing some configs. Historically, this was less
useful in games since console hardware is pretty well-standardized, but
as more games target a heaping hodgepodge of mobile devices, this is
becoming more relevant.</p>
</li>
<li>
<p><em>It’s complex.</em> Unlike the previous solutions, this one is pretty
heavyweight. You have to create some configuration system, possibly
write code to load and parse a file, and generally <em>do some stuff</em> to
locate the service. Time spent writing this code is time not spent on
other game features.</p>
</li>
<li>
<p><em>Locating the service takes time.</em> And now the smiles really turn to
frowns. Going with runtime configuration means you’re burning some CPU
cycles locating the service. Caching can minimize this, but that still
implies that the first time you use the service, the game’s got to go
off and spend some time hunting it down. Game developers <em>hate</em> burning
CPU cycles on something that doesn’t improve the player’s game
experience.</p>
</li>
</ul>
</li>
</ul>
<h3><a href="#what-happens-if-the-service-can't-be-located" name="what-happens-if-the-service-can't-be-located">What happens if the service can’t be located?</a></h3>
<ul>
<li>
<p><strong>Let the user handle it:</strong></p>
<p>The simplest solution is to pass the buck. If the locator can’t find the
service, it just returns <code>NULL</code>. This implies:</p>
<ul>
<li>
<p><em>It lets users determine how to handle failure.</em> Some users may consider
failing to find a service a critical error that should halt the game.
Others may be able to safely ignore it and continue. If the locator
can’t define a blanket policy that’s correct for all cases, then passing
the failure down the line lets each call site decide for itself what the
right response is.</p>
</li>
<li>
<p><em>Users of the service must handle the failure.</em> Of course, the corollary
to this is that each call site <em>must</em> check for failure to find the
service. If almost all of them handle failure the same way, that’s a lot
duplicate code spread throughout the codebase. If just one of the
potentially hundreds of places that use the service fails to make that
check, our game is going to crash.</p>
</li>
</ul>
</li>
<li>
<p><strong>Halt the game:</strong></p>
<p>I said that we can’t <em>prove</em> that the service will always be available at
compile-time, but that doesn’t mean we can’t <em>declare</em> that availability is
part of the runtime contract of the locator. The simplest way to do this is
with an assertion:</p>
<div class="codehilite"><pre><span class="k">class</span> <span class="nc">Locator</span>
<span class="p">{</span>
<span class="nl">public:</span>
<span class="k">static</span> <span class="n">Audio</span><span class="o">&</span> <span class="n">getAudio</span><span class="p">()</span>
<span class="p">{</span>
<span class="n">Audio</span><span class="o">*</span> <span class="n">service</span> <span class="o">=</span> <span class="nb">NULL</span><span class="p">;</span>
<span class="c1">// Code here to locate service...</span>
<span class="n">assert</span><span class="p">(</span><span class="n">service</span> <span class="o">!=</span> <span class="nb">NULL</span><span class="p">);</span>
<span class="k">return</span> <span class="o">*</span><span class="n">service</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">};</span>
</pre></div>
<p>If the service isn’t located, the game stops before any subsequent code
tries to use it. The <span name="assert"><code>assert()</code></span> call there doesn’t solve the problem of
failing to locate the service, but it does make it clear whose problem it
is. By asserting here, we say, “Failing to locate a service is a bug in the
locator.”</p>
<aside name="assert">
<p>The <a href="singleton.html" class="pattern">Singleton</a> chapter
explains the <code>assert()</code> function if you’ve never seen it before.</p>
</aside>
<p>So what does this do for us?</p>
<ul>
<li>
<p><em>Users don’t need to handle a missing service.</em> Since a single service
may be used in hundreds of places, this can be a significant code
saving. By declaring it the locator’s job to always provide a service,
we spare the users of the service from having to pick up that slack.</p>
</li>
<li>
<p><em>The game is going to halt if the service can’t be found.</em> On the off
chance that a service really can’t be found, the game is going to halt.
This is good in that it forces us to address the bug that’s preventing
the service from being located (likely some initialization code isn’t
being called when it should), but it’s a real drag for everyone else
who’s blocked until it’s fixed. With a large dev team, you can incur
some painful programmer downtime when something like this breaks.</p>
</li>
</ul>
</li>
<li>
<p><strong>Return a null service:</strong></p>
<p>We showed this refinement in our sample implementation. Using this means:</p>
<ul>
<li>
<p><em>Users don’t need to handle a missing service.</em> Just like the previous
option, we ensure that a valid service object will always be returned,
simplifying code that uses the service.</p>
</li>
<li>
<p><em>The game will continue if the service isn’t available.</em> This is both a
boon and a curse. It’s helpful in that it lets us keep running the game
even when a service isn’t there. This can be really helpful on a large
team when a feature we’re working on may be dependent on some other
system that isn’t in place yet.</p>
<p>The downside is that it may be harder to debug an <em>unintentionally</em>
missing service. Say the game uses a service to access some data and
then make a decision based on it. If we’ve failed to register the real
service and that code gets a null service instead, the game may not
behave how we want. <span name="null">It</span> will take some work to
trace that issue back to the fact that a service wasn’t there when we
thought it would be.</p>
<aside name="null">
<p>We can alleviate this by having the null service print some debug output
whenever it’s used.</p>
</aside>
</li>
</ul>
</li>
</ul>
<p>Among these options, the one I see used most frequently is simply asserting that
the service will be found. By the time a game gets out the door, it’s been very
heavily tested, and it will likely be run on a reliable piece of hardware. The
chances of a service failing to be found by then are pretty slim.</p>
<p>On a larger team, I encourage you to throw a null service in. It doesn’t take
much effort to implement, and can spare you from some downtime during
development when a service isn’t available. It also gives you an easy way to
turn off a service if it’s buggy or is just distracting you from what you’re
working on.</p>
<h3><a href="#what-is-the-scope-of-the-service" name="what-is-the-scope-of-the-service">What is the scope of the service?</a></h3>
<p>Up to this point, we’ve assumed that the locator will provide access to the
service to <em>anyone</em> who wants it. While this is the typical way the pattern is
used, another option is to limit access to a single class and its descendants,
like so:</p>
<div class="codehilite"><pre><span class="k">class</span> <span class="nc">Base</span>
<span class="p">{</span>
<span class="c1">// Code to locate service and set service_...</span>
<span class="nl">protected:</span>
<span class="c1">// Derived classes can use service</span>
<span class="k">static</span> <span class="n">Audio</span><span class="o">&</span> <span class="n">getAudio</span><span class="p">()</span> <span class="p">{</span> <span class="k">return</span> <span class="o">*</span><span class="n">service_</span><span class="p">;</span> <span class="p">}</span>
<span class="nl">private:</span>
<span class="k">static</span> <span class="n">Audio</span><span class="o">*</span> <span class="n">service_</span><span class="p">;</span>
<span class="p">};</span>
</pre></div>
<p>With this, access to the service is restricted to classes that inherit <code>Base</code>.
There are advantages either way:</p>
<ul>
<li>
<p><strong>If access is global:</strong></p>
<ul>
<li>
<p><em>It encourages the entire codebase to all use the same service.</em> Most
services are intended to be singular. By allowing the entire codebase to
have access to the same service, we can avoid random places in code
instantiating their own providers because they can’t get to the “real”
one.</p>
</li>
<li>
<p><em>We lose control over where and when the service is used.</em> This is the
obvious cost of making something global — anything can get to it. The <a
class="gof-pattern" href="singleton.html">Singleton</a> chapter has a
full cast of characters for the horror show that global scope can spawn.</p>
</li>
</ul>
</li>
<li>
<p><strong>If access is restricted to a class:</strong></p>
<ul>
<li>
<p><em>We control coupling.</em> This is the main advantage. By limiting a service
to a branch of the inheritance tree, we can make sure systems that
should be decoupled stay decoupled.</p>
</li>
<li>
<p><em>It can lead to duplicate effort.</em> The potential downside is that if a
couple of unrelated classes <em>do</em> need access to the service, they’ll
each need to have their own reference to it. Whatever process is used to
locate or register the service will have to be duplicated between those
classes.</p>
<p>(The other option is to change the class hierarchy around to give those
classes a common base class, but that’s probably more trouble than it’s
worth.)</p>
</li>
</ul>
</li>
</ul>
<p>My general guideline is that if the service is restricted to a single domain in
the game, then limit its scope to a class. For example, a service for getting
access to the network can probably be limited to online classes. Services that
get used more widely like logging should be global.</p>
<h2><a href="#see-also" name="see-also">See Also</a></h2>
<ul>
<li>
<p>The Service Locator pattern is a sibling to <a class="gof-pattern"
href="singleton.html">Singleton</a> in many ways, so it’s worth looking at
both to see which is most appropriate for your needs.</p>
</li>
<li>
<p>The <a href="http://unity3d.com">Unity</a> framework uses this pattern in concert with
the <a href="component.html" class="pattern">Component</a> pattern in its
<a href="http://docs.unity3d.com/412/Documentation/ScriptReference/Component.GetComponent.html?from=index"><code>GetComponent()</code></a> method.</p>
</li>
<li>
<p>Microsoft’s <a href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game.services.aspx">XNA</a> framework for game development has this pattern built
into its core <code>Game</code> class. Each instance has a <code>GameServices</code> object that
can be used to register and locate services of any type.</p>
</li>
</ul>
<nav>
<span class="prev">← <a href="event-queue.html">Previous Chapter</a></span>
<span class="next"><a href="optimization-patterns.html">Next Chapter</a> →</span>
<span class="toc">≡ <a href="/">The Book</a></span>
</nav>
</div>
</div>
<footer>© 2009-2014 Robert Nystrom</footer>
</body>
</html>