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.
Self implemented singletons are an anti-pattern. The need to inherit, and lock your classes into a specific form goes away if you just implement a factory:
However, you’re really using the factory as a service locator and service locator is also considered an anti-pattern as you can easily just use DI to inject the Server instance into your consuming classes.
Windsor style registration:
Notice that the word singleton is never mentioned? You still get ‘a single instance of an object’, but you don’t have to write code to maintain that relationship, and your classes are not constrained and corrupted by the concept of ‘singleton’ from the start