Singleton is a common pattern implemented in both native libraries of .NET and J
ID: 642025 • Letter: S
Question
Singleton is a common pattern implemented in both native libraries of .NET and Java. You will see it as such:
C#: MyClass.Instance
Java: MyClass.getInstance()
The question is: when writing APIs, is it better to expose the singleton through a property or getter, or should I hide it as much as possible?
Here are the alternatives for illustrative purposes:
Exposed(C#):
private static MyClass instance;
public static MyClass Instance
{
get {
if (instance == null)
instance = new MyClass();
return instance;
}
}
public void PerformOperation() { ... }
Hidden (C#):
private static MyClass instance;
public static void PerformOperation()
{
if (instance == null)
{
instance = new MyClass();
}
...
}
Explanation / Answer
I think hiding Singleton is a bad idea. If you don't have a way to get a reference to the created instance via a getInstance() method, how you are going to do it considering that Singleton classes do not have public constructors? There is no way to get that reference. That means that if you decide to "hide" the Signbleton, your only option is to check in every public static method of the Signletone class whether the instance was already instantiated and if not, do it. So your code becomes something like this:
class BadSingletone {
private static MyClass instance;
public static void PerformOperation()
{
if (instance == null) { instance = new MyClass(); }
...
}
public static void PerformSomeOtherOperation()
{
if (instance == null) { instance = new MyClass(); }
...
}
public static void PerformYetAnotherOperation()
{
if (instance == null) { instance = new MyClass(); }
...
}
}
littered with all those instantiation checks. You can of course encapsulate the check in a separate function but you will again have to call it in every public static function of the class. And what if you accidentially forget to include it in one of the functions? Users of the class will not be too happy about it.
So, to my mind, hiding Singleton does not make sense - it makes you litter your code with unneccessary checks.