Should I pass my service locator to all of my objects when they need them?

I recently decided that a service locator would be a good design pattern for accessing important managers for my game, as a world manager (can create objects and track them) and sound manager. However, I am not sure what is the most appropriate way to access the service locator. I started by passing a pointer to a service locator, which I used mostly, but that gets tedious as I found everything (projectiles, players, everything!) Needs arguments in it.

I'm asking this here because I don't think it's game specific, but if I'm wrong, just let me know.

Am I cheating on this pattern? Thank you for your time.

EDIT: Will this singleton solve this problem? They have a global hotspot, but I don't think this is the cleanest solution. Any ideas? Or would it be better?

+3


source to share


2 answers


This is a situation where using a global variable (or Singleton) might be appropriate. You have to weigh the disadvantages of using the global / a singleton variable against the convenience of not passing a reference almost everywhere. If you think that flaws are unlikely to affect your design / code, then using a global variable can make your code much cleaner.

Some disadvantages of using a global variable:

  • Managing the lifetime of your global can be more complex. If you are defining multiple globals in different translation units (cpp files), the order in which they are created is not defined, so it is best for them not to rely on each other during instantiation. One solution would be to store global pointers and create objects somewhere at the beginning of your program (for example, mostly), but then you have to make sure that you don't create dangling pointers during the destruction phase of your program.
  • You may need to synchronize access to your global variable (s) in a multithreaded context. With global variables, it is harder to use objects on a thread (or proxy) to prevent access synchronization.


Additional singleton disadvantages can be:

  • There is no way to create copies of your class eg. to save or cancel.
+1


source


Personally, I advocate using a single context object everywhere, rather than using single ones. Ask the context object to provide you with functions that will give you pointers / links or access to all the different services, managers, etc.



0


source







All Articles