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:
Edit:
The Singleton pattern requires a private constructor and this already makes subclassing impossible. You'll need to rethink your design. The Abstract Factory pattern may be more suitable for the particular purpose. The purpose of the private constructor in the Singleton is to prevent anyone else instantiating it.
Most other languages simply do not allow defining abstract singleton class methods (for example, static methods in TypeScript, C++, Java, C#, and more are not allowed to be abstract).
Yes you can. Keep base class constructor protected (and not private). Then derived class can be instantiated but base class cannot be (even inside function definitions of derived class).
Singletons leave a trail of confusion Bugs might stay hidden even when you're testing. It's very difficult to write unit tests for code that uses singletons because it is generally tightly coupled with the singleton instance.
No you can't because when you want to use new T()
you should have a public constructor for it, and it's different from singleton definition. because in singleton you should have a private constructor, and in this case (public one) everyone can create new instance of your object and it's not a singleton.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With