I found that in C # you can implement the Singleton class as follows:
class Singleton { private static Singleton _instance; public static Singleton Instance { get { return _instance ?? (_instance = new Singleton()); } } protected Singleton() { } }
What works for instances of type Singleton , ie:
var a = Singleton.Instance; var b = Singleton.Instance; Console.WriteLine(ReferenceEquals(a, b));
But what if I want the derived Singleton classes to also match the Singleton pattern, that is:
class A:Singleton { ... } A a = A.Instance;
In this case, the Instance static member gains access to the Singleton class and creates a Singleton instance that is not the target. In addition, there are two main problems with this solution:
- A derived class may implement its own constructor and lose the Singleton pattern.
- If there is another instance of
Singleton , then the derived class will refer to the less derived instance.
My question is: Is there another way to implement the Singleton class in C #, ensuring that the derived class is also single?
source share