Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing singleton inheritable class in C# [duplicate]

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:

  • The derived class can implement its own constructor and lose the Singleton Pattern.
  • If there is another instance of Singleton then the derived class is going to reference that less-derived instance

My question is: Is there another way to implement a Singleton class in C# ensuring that derived class are also singleton?

like image 769
Robin Curbelo Avatar asked May 31 '13 20:05

Robin Curbelo


1 Answers

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.

like image 160
Moo-Juice Avatar answered Sep 25 '22 21:09

Moo-Juice