This might sound like a weird idea and I haven’t thought it through properly yet.
Say you have an application that ends up requiring a certain number of singletons to do some I/O for example. You could write one singleton and basically reproduce the code as many times as needed.
However, as programmers we’re supposed to come up with inventive solutions that avoid redundancy or repetition of any kind. What would be a solution to make multiple somethings that could each act as a singleton.
P.S: This is for a project where a framework such as Spring can’t be used.
You could introduce an abstraction like this:
Then for each singleton, you just need to write this:
Then you can use the singletons by writing
database.get(). If the singleton hasn’t been created, it is created and initialized.The reason people probably don’t do this, and prefer to just repeatedly write something like this:
Is because in the end it is only one more line of code for each singleton, and the chance of getting the initialize-singleton pattern wrong is pretty low.