Hide or Show singleton?
Posted
by
Sinker
on Programmers
See other posts from Programmers
or by Sinker
Published on 2013-07-01T11:56:45Z
Indexed on
2013/07/01
16:29 UTC
Read the original article
Hit count: 158
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 :)
© Programmers or respective owner