I found that in C# you can implement a Singleton class, as follows:
class Singleton
{
private static Singleton _instance;
public static Singleton Instance => _instance ??= new Singleton();
protected Singleton() { }
}
Which works for instances of type Singleton
, i.e:
var a = Singleton.Instance;
var b = Singleton.Instance;
Console.WriteLine(ReferenceEquals(a, b)); //Prints True.
But what if I want that derived classes of Singleton also follow the Singleton pattern, i.e:
class A:Singleton
{ ... }
A a = A.Instance;
In this case the static member Instance
is accessed by Singleton
class and creates a Singleton
instance, which isn't the objective.
Besides, there are two main problems with this solution:
Singleton
then the derived class is going to reference that less-derived instanceMy question is: Is there another way to implement a Singleton class in C# ensuring that derived class are also singleton?
Ignoring the usual "Don't use a Singleton, look at your design." arguments, you could conceivably implement one as thusly (assuming your derived classes have default constructors):
public abstract class Singleton<T> where T : class, new()
{
private static T _instance;
public static T GetInstance()
{
if(_instance == null)
_instance = new T();
return _instance;
}
}
And derive like this:
public class SingletonA : Singleton<SingletonA> { /* .... */ }
public class SingletonB : Singleton<SingletonB> { /* .... */ }
But, I really don't advocate this singleton approach personally. They do have their (rare) uses, but they can turn out to be more of a pain in the bum - turning in to glorified global variable containers.
Also, be mindful of thread-safety.
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