A (hopefully) basic question about singleton instances
Hello,
I don't know why but I am mixing things up in my head today with the singleton pattern. So the basic pattern goes something like this (simplified for brevity):
Now, in my head I had it that the private
_instance
variable should be an instance variable, i.e. not static. But all examples of the singleton pattern that I have found have the private instance being static. So why is this? Is there a problem with it being an instance variable? Is this just to absolutely ensure that there can only be one instance? I don't have any problem with using a private static field but it was in my head that it shouldn't be so I'd like to understand why I thought that and why it is wrong to do so.6 Replies
It's to make sure that there is only one intance of the class throughout the application.
It's static so that only one can exist, on the type itself
If it was an instance member, you would need... an instance
Since you can have multiple instances, it's no longer a singleton
Unless in the context of dependency injection, and the class being injected as a singleton
@ZZZZZZZZZZZZZZZZZZZZZZZZZ You too fast for me...imma wait for you to go to bed lmao
That won't happen for another 16-ish hours lol
Ayt, so we gonna duo this lmao
:picard_facepalm: I think I need a holiday. This is so obvious
thank you