On design patterns: When should I use the singleton?
class Singleton
{
private static Singleton instance;
private Singleton() {}
Assuming your question is in the title:
I once worked with a COM object that could only have one instance per server. We exposed it to the entire ASP.NET application through a singleton.
This is not a singleton as a singleton provides the thread safety with readonly keywords.
For example,
public sealed class Singleton
{
// private static Singleton instance; (instead of this, it should be like this, see below)
private static readonly Singleton instance = new Singleton();
static Singleton(){}
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
instance = new Singleton();
return instance;
}
}
}
By using this it will provide the tread safety and proper singleton pattern (that is how it is different from a static class). Your code for the singleton were not thread safe.
For more about singleton, check these links:
In my project we created a logger component which is getting used for logging in the application to different sources (e.g. text file, XML, and database, based on configurations). So there is a log manager which creates the only one instance of the logger class across the application for logging the message, errors, etc.
You should use a Singleton when there should only be one instance of an object. However, Misko Hevery has some thoughts on why Singletons are bad!