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();
}
...
}
EDIT:
There seems to be a number of detractors of the Singleton design. Great! Please tell me why and what is the better alternative. Here is my scenario:
My whole application utilises one logger (log4net/log4j). Whenever, the program has something to log, it utilises the Logger
class (e.g. Logger.Instance.Warn(...)
or Logger.Instance.Error(...)
etc. Should I use Logger.Warn(...)
or Logger.Warn(...)
instead?
If you have an alternative to singletons that addresses my concern, then please write an answer for it. Thank you 🙂
10
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.
7
Technically, I don’t believe it’s still considered a singleton pattern unless you expose the instance to other classes. It’s just a private static member. That being said, in general the smaller the scope of a variable, the better. If other classes don’t need it, don’t share it. However, in most cases it’s going to be much simpler just to instantiate the static member at declaration instead of checking everywhere if it’s already been instantiated.
3