I have a singleton instance that is referenced throughout the project which works like a charm. It saves me the trouble from having to pass around an instance of the object to every little class in the project. However, now I need to manage multiple instances of the previous setup, which means that the singleton pattern breaks since each instance would need it’s own singleton instance.
What options are there to still maintain static access to the singleton? To be more specific, we have our game engine and several components and plugins reference the engine through a static property. Now our server needs to host multiple game instances each having their own engine, which means that on the server side the singleton pattern breaks.
I’m trying to avoid all the classes having the engine in the constructor.
Edit: The engines isn’t guaranteed to be running on a unique thread. Each engine has a unique ID that can be used to identify the instance.
The closest thing you might be able to do is use the
ThreadStaticattribute on your singleton instance variable. This will maintain static semantics in terms of access, but each thread will have its own instance.That being said, that could very easily not be what you want. If you need to have either multiple threads access the same instance via the static variable or have one thread access different instances by the same variable, then this won’t work.
Put another way, this will work if both of the following are true:
Otherwise, you’ll likely have to go the factory pattern route, where each engine passes some sort of identifying information (even if it’s just
this) to a static function to obtain the instance rather than just using theInstanceproperty.