How do I make an abstract class that shall force each derived classes to be Singleton ? I use C#.
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.
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).
A class derived from an abstract base class will also be abstract unless you override each pure virtual function in the derived class. The compiler will not allow the declaration of object d because D2 is an abstract class; it inherited the pure virtual function f() from AB .
To create a singleton class using Lazy Initialization method, we need to follow the below steps: Declare the constructor of the class as private. Create a private static instance of this class but don't initialize it. In the final step, create a factory method.
When you want to enfore compile time checking, this is not possible. With runtime checking you can do this. It's not pretty, but it's possible. Here's an example:
public abstract class Singleton
{
private static readonly object locker = new object();
private static HashSet<object> registeredTypes = new HashSet<object>();
protected Singleton()
{
lock (locker)
{
if (registeredTypes.Contains(this.GetType()))
{
throw new InvalidOperationException(
"Only one instance can ever be registered.");
}
registeredTypes.Add(this.GetType());
}
}
}
public class Repository : Singleton
{
public static readonly Repository Instance = new Repository();
private Repository()
{
}
}
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