I started a component based, networked game (so far only working on the server). I know why singletons can be bad, but I can't think of another way to implement the same thing. So far I have:

  • A GameState singleton (for managing the global state of the game, i.e. pre-game, running, exiting).

  • A World singleton, which is the root entity for my entity graph

  • An EntityFactory

  • A ComponentFactory

  • I'm thinking about adding a "MessageDispatcher" so individual components can subscribe to network messages.

The factories do not have state, so I suppose they aren't so bad. However, the others do have global state, which is asking for trouble. How can I refactor my code so it uses fewer singletons?


You could turn the EntityFactory and ComponentFactory modules into namespaces, since they don't have state. This will effectively cut the number of singletons in your code by 50% ;). Also, you don't have to make the world entity a singleton. You could make it an entity created from the factory just like all the other entities. Then you could have a game with multiple worlds! But that really depends in what your goal is. If you do manage to go that route though, you'll have been able to reduce your singleton usage by 75%!

| improve this answer | |
  • \$\begingroup\$ Really good points, thanks. I can do all of these :) \$\endgroup\$ – Tamás Szelei Nov 5 '12 at 15:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.