This is my abstract class which must be derived each time I want to make a Singleton:
public abstract class Singleton<T> where T : Singleton<T>
{
private static readonly Lazy<T> _instance = new Lazy<T>(() =>
{
var constructor = typeof(T).GetConstructor(BindingFlags.NonPublic |
BindingFlags.Instance, null, new Type[0], null);
return (T)constructor.Invoke(null);
});
public static T Instance { get { return _instance.Value; } }
public Singleton() { }
}
So, every time I need to follow the Singleton design pattern, I can just make this:
sealed class Server : Singleton<Server>
{
private Server() { }
...
}
Is this completely right, and, if not, why?
Edit:
- Added private constructor on derived class example and invoking on abstract base.
Edit:
- Reworked type parameter initialization.