Game Development Reference
In-Depth Information
A singleton is a design pattern in which only one instance of an object should ever exist.
Singletons may appear like a great solution when you first think about certain types of sys-
tems. Quite often high level manager type systems are quickly considered as singleton can-
didates. In practice however, the decision to use a singleton should not be made lightly, giv-
en some shortcomings and potential problems we will discuss.
One ofthe biggest problems with singletons is that they donot evolve well when the project
requirements change. In many cases singletons will end up as a repository of special case
testsbecausethesingleton endsupinuseinunexpectedplaces;oftenpollutingthecodebase
in which it needs to be included.
Many problems that seemingly require a singleton to work can be solved by a more diligent
analysis of the situation. Given that a singleton guarantees a single instance of an object in
existence, it also provides a global access to the object. But many times a global object is
throughout the game codebase. In games a problem that may occur is when the technology
is being developed assuming it will only power single player games, so singletons are used
for a variety of game and UI systems. When the concept of multiple players is implemented
the singleton pattern begins to break, at best the singletons will be refactored to be a mem-
ber of another high level system, such as the player object itself, but this may represent a
significant amount of work and in many cases the singleton is retrofitted to work in the new
architecture, and this can lead to a nightmare to maintain.
That said, there are valid use cases for singletons, good candidates are abstract code factor-
ies,thesearecodeconstructsthatcreateinstances ofotherobjects.Anotherpossiblecandid-
ate for a singleton is the localization system, the benefit of which is that we have a single
and straightforward.
A very common but very weak implementation of the singleton pattern makes use of a local
static object to ensure only one instance is ever created.
template <class T>
class singleton
static T& Get()
Search WWH ::

Custom Search