开发者

Can we inherit singleton class?

开发者 https://www.devze.com 2023-01-13 04:37 出处:网络
Can we inherit singleton开发者_开发知识库 class?It depends on implementation. Singletons usually have private constructor and possibly marked sealed, if it is so then you can\'t. If it is at least pro

Can we inherit singleton开发者_开发知识库 class?


It depends on implementation. Singletons usually have private constructor and possibly marked sealed, if it is so then you can't. If it is at least protected you can. If you just inherit from singleton class, result will not be singleton so you should follow the pattern and make it also singleton.


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). I've tried this and it works well.


If you cannot inherit from a singleton class, you might as well have implemented that class using only static methods, properties, fields and events.

Being able to access an object of a derived class through a static method (or property) of the base class is one of the key concepts of the Singleton pattern. To quote from Design Patterns: Elements of Reusable Object-Oriented Software (Gamma et. al.):

Applicability

Use the Singleton pattern when

  • there must be exactly one instance of a class, and it must be accessible to clients from a well-known access point.
  • when the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code.

(emphasis by me)


Here's a possible way to handle a derived Singleton:

public abstract class Singleton<T> where T : Singleton<T>, new() {

    private static readonly T s_instance = new T();

    protected Singleton() {
        if (s_instance != null) {
            string s = string.Format(
                "An instance of {0} already exists at {0}.instance. " +
                "That's what \"Singleton\" means. You can't create another.",
                typeof(T));
            throw new System.Exception(s);
        }
    }

    public static T instance { get { return s_instance; } }
}

public class MyClass : Singleton<MyClass> {


}


Sure. Why not? The inheriting class will be a specialization of the base Singleton class.

Instances of each of these classes (the base class and the specialized one) will be completely separate. In other words, their Instance members will point to separate objects.


Only the singleton class itself can create an instance... so I supposse the answer is not. I think you can do it, but then it will not be a singleton any more :D

0

精彩评论

暂无评论...
验证码 换一张
取 消