This is how I write my singleton classes.
public class MyClass
{
/// <summary>
/// Singleton
/// </summary>
private static MyClass instance;
/// <summary>
/// Singleton access.
/// </summary>
public static MyClass Instance
{
get
{
if (_instance == null)
{
_instance = new MyClass();
}
return _instance;
}
}
private MyClass() { .... }
}
How To Create A Singleton Pattern That Is Reusable?
Singleton patterns present the following challenges.
- The constructor is
private
orprotected
. - A base class can't instantiate an inherited class. So you can reuse a common abstract
MyAbstractSingletonClass
. - It has to have a local read-only property to get the instance.
The Problem
I'm using this pattern on a number of classes and always have to write the same code. How can I write something that is reused whenever I need a singleton?