0

I have a class in my game called Core where most Managers reside. They go here because all my resources, language data, bitmaps, sounds get loaded by the managers when the game starts up.

After that, the scene manager is created and it initializes the first scene.

The issue comes with sharing data from upper level classes to lower level classes such as scenes.

When a scene starts, it needs to request bitmaps and sounds from the managers. Most scenes also need to look up words to put on buttons based on the language.

The way I do this is by having a sort of Manager manager class. It is constructed with each type of manager that most scenes use. This is passed to the scene manager which passes a pointer to the current scene.

This means each time I have a new manager, I need to change the constructor of the Manager manager and change a few things in the scene manager.

Is there a better way to do this? How is this sort of thing usually done?

Thanks

jmasterx
  • 47,653
  • 87
  • 281
  • 523

3 Answers3

2

The most common way of doing this is with a singleton. Just because it's common though, doesn't mean it is the best way.

A different way to do the same thing is dependency injection. The constructor for a class will take pointers to the managers that it requires. This gives the advantage of collecting all the dependencies in one place, and lets you substitute test code for any manager easily.

Mark Ransom
  • 271,357
  • 39
  • 345
  • 578
0

For global available functions and data i would recommend you the singleton pattern. If you need to have different data for different scenes you should consider using a multi-singleton (pass strings to the getInstance function) or writing a interface which has functions to access data by strings/names like the Property class in java.

Sebastian Hoffmann
  • 10,024
  • 5
  • 43
  • 74
  • Singletons? Isn't that an anti-pattern now? – Lalaland Jan 06 '12 at 22:54
  • 1
    Its still widely spread and i dont see the point why i should reject a solution just because it isnt much in vogue anymore – Sebastian Hoffmann Jan 06 '12 at 22:58
  • 1
    @paranaix: Maybe there is some reason why it's not considered good enough any longer.. – tp1 Jan 07 '12 at 00:06
  • There are a [few reasons](http://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons) to avoid singletons, especially in C++. I owe some of my grey hairs to fixing or working around badly implemented singletons; and more to having to introduce multiple instances of classes deliberately designed to prevent that. – Mike Seymour Jan 07 '12 at 01:56
0

Have a singleton class Root which holds all of the managers. During initialization, the Root object constructs all of the managers. You can then add get functions for all of the managers.

This works really well, because from anywhere in the code you can call

Root::getPtr()->getTextureManager()->whatever()
carpat
  • 831
  • 10
  • 24