I'm trying to design a more flexible form of Singleton.
The problems I'm trying to address are the following:
- Singletons cannot be tested easily.
- They abuse the object oriented approach by not allowing inheritance, the code becomes linear and many developers tend to over-use them.
- They are limited to one instance, in the sense of duplicating the same mechanism without duplicating the class itself (e.g., the way ThreadPool operates as a singleton for every application, but every application has its own instance).
Now, the solution I came up with so far is the following:
- Make the Singleton class a regular public class with an internal constructor (accessible only by classes of the same package).
- As with every product-oriented class, all static properties and
static constants were moved to an internal
SingletonShared
class that will be passed as a parameter to the Singleton's constructor. Those two are hidden behind a publicSingletonFactory
, that has the static methodgetInstance(key)
. - In case we're dealing with a more complex system, where each
singleton requires it's own unique set of parameters, I added a
static method of
setAdapter(adapter)
to theSingletonFactory
. Using the methodgetShared(key)
, a class that implementsISingletonAdapter
should return theSingletonShared
value of that instance (e.g.,SingletonXmlAdapter
is passed an Xml file to the constructor, and deserializes a certain node based on the key it was given).
All of the above are packed as a Singleton
package.
Now, for test-ability purposes, there is an option of marking Singleton as an internal class and have it implement an ISingleton
public interface.
Questions:
- Is this solution acceptable?
- Is there a better / cleaner / shorter way of achieving the same effect?
- Which version is best (Singleton as internal vs. constructor as internal)?
Thanks!