Game Development Reference
In-Depth Information
Chapter 23
Useful Design Patterns for Game
Development
Design patters are like blueprints for your code. They are systems you can use to complete tasks
that are very similar in nature that arise while you are developing games. Just as STL data structures
are reusable collections that can be used when needed to solve specific problems, design patterns
can be utilized to solve logical problems in your code.
There are benefits to using design patterns in your game projects. First, they allow you to use a
common language that many other developers will understand. This helps reduce the length of time
it takes new programmers to get up to speed when helping on your projects because they might
already be familiar with the concepts you have used when building your game's infrastructure.
Design patterns can also be implemented using common code. This means that you can reuse this
code for a given pattern. Code reuse reduces the number of lines of code in use in your game, which
leads to a more stable and more easily maintainable code base, both of which mean you can write
better games more quickly.
You've already seen at least one design patter used in this topic already. Chapter 21 showed how
you could use a template class to create a Singleton object. You can think of a Singleton as a
reusable logical object that provides you with the ability to ensure that only a single instance of a
given class is created and accessed throughout your game code. This chapter introduces you to
three more patterns: the Factory, the Observer and the Visitor.
Using the Factory Pattern in Games
The factory pattern is a useful way to abstract out the creation of dynamic objects at runtime.
A factory for our purposes is simply a function that takes a type of object as a parameter and returns
a pointer to a new object instance. The returned object is created on the heap and therefore it is the
caller's responsibility to ensure that the object is deleted appropriately. Listing 23-1 shows a factory
method that I have created to instantiate the different types of Option objects used in Text Adventure.
239
 
Search WWH ::




Custom Search