代码之家  ›  专栏  ›  技术社区  ›  Ram

我们能继承单例类吗?

  •  10
  • Ram  · 技术社区  · 15 年前

    我们能继承单例类吗?

    6 回复  |  直到 15 年前
        1
  •  22
  •   Andrey    15 年前

    这取决于执行情况。单例通常有私有构造函数,并且可能被标记为 sealed ,如果是这样的话,你就不能。如果它至少得到了保护,你就可以。如果您只是从singleton类继承,那么结果将不是singleton,所以您应该遵循该模式并使其也是singleton。

        2
  •  3
  •   Atul    12 年前

    是的,你可以。保持基类构造函数受保护(而不是私有的)。

    然后可以实例化派生类,但不能实例化基类(即使在派生类的函数定义内部)。我试过这个,效果很好。

        3
  •  2
  •   Community Mohan Dere    5 年前

    如果不能从单例类继承,那么最好只使用静态方法、属性、字段和事件来实现该类。

    设计模式:可重用面向对象软件的元素 (Gamma等人):

    适用性

    • 什么时候 唯一的实例应该通过子类化来扩展 ,客户应该能够 使用扩展实例而不修改其代码

    (我强调)

        4
  •  2
  •   k76    8 年前

    下面是一种处理派生单例的可能方法:

    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> {
    
    
    }
    
        5
  •  0
  •   Emmanuel    15 年前

    当然。为什么不?继承类将是基本单例类的特殊化。

    每个类(基类和专用类)的实例都是完全独立的。换句话说,它们的实例成员将指向不同的对象。

        6
  •  0
  •   Jonathan    15 年前

    只有singleton类本身可以创建一个实例。。。所以我想答案不是。我想你能做到,但那就不再是单身了