Game Development Reference
tializing the other players as well. This is one side effect of classes strongly dependent
on each other, also known as tight coupling . The more classes are tightly coupled with
each other, the harder it is to make changes to any part of your code. It's like mixing
cement that's slowly drying up until it's so hard that any change is easier to do by hack-
ing it instead of improving the code. That's the point where bugs seem to occur every-
where, at random, with no connection to a recent change. In one word: frustrating.
The more you rely on singletons, the more likely such issues will arise. Before creating
a singleton class, always consider whether you really need only one instance of this
class and its data and whether that might change later.
I understand it's hard for a beginner to judge when and where to use a singleton, partic-
ularly if you haven't had much experience with object-oriented programming. The
Q&A web site Stackoverflow.com hosts a discussion with additional links that illus-
trates the controversy around the Singleton design pattern and gives some food for
My advice is to study popular uses of singletons. The use of singletons in the cocos2d
game engine for resource management is perfectly fine, because it simplifies the over-
all design of the game engine. Most other game engines use singletons for similar pur-
poses as well, and I've rarely heard anyone complain about that. You'll even find
singletons in the iOS SDK. Singletons are generally not as bad as some make them
sound like, although they do tend to be very problematic by introducing strong depend-
encies, and the problems grow exponentially with the size of the code base.
Cocos2d Test Cases
Did you know that cocos2d comes with a lot of sample code? In your cocos2d-iphone
folder, you'll find a project aptly named cocos2d-ios.xcodeproj that contains a lot of
test targets you can build and run. You can see how things work and then check the
code to see how it's implemented.
But I'm also somewhat hesitant to recommend the test cases because you'll see a lot of
nonstandard code. Some of the tests are downright sloppy. After all, the code was writ-
ten just to test that the code is working. It wasn't written to teach best programming
practices. So take everything you see in the test cases with a grain of salt.