返回后代的单例实例

我有几个单例类,所以我尝试用方法GetInstance(params)和派生类创建一个父BaseClass,它应该实现这个方法并返回自己的实例(所以我不必抛出它们)… as它们是单例,方法应该是静态的,但不允许覆盖静态方法。 编码它的最佳方法是什么? 我想要的示例代码:

public class Base { public static virtual T GetInstance() where T : class; } public class Derived { Derived instance; public static override T GetInstance() where T : typeOf(this){ if (instance == null) { instance = new Derived(); } return instance; } } 

在我想要打电话的外面的代码中

 Derived.GetInstance().SomeDerivedMethod() 

 (Derived.GetInstance() as Derived).SomeDerivedMethod() and not new Derived().getInstance().SomeDerivedMethod() 

我知道这不好,而且我对T型也缺乏经验,所以欢迎任何建议。 谢谢

编辑:

或者,如果有可能以某种方式在Base中定义GetInstance()方法,那么派生类不需要对它进行ovwerride,但是它将从调用它的位置返回类的实例… Derived.GetInstance()将返回实例衍生的

您可以为单个Dictionary使用Dictionary 。 下面的方法要求每种类型都实现私有的构造函数。 当然,如果单例字典中已经存在该类的实例,您还可以检查每个派生类。 这甚至可以避免某人使用Activator来创建实例。

未经测试:

 public class Base { static Dictionary _Singletones = new Dictionary(); public static T GetInstance() where T : class { Type t = typeof(T); if (_Singletones.ContainsKey(t)) return _Singletones[t] as T; else { // Create instance by calling private constructor and return it T result = Activator.CreateInstance(t, true) as T; _Singletones.Add(t, result); return result; } } } 

尝试抽象工厂设计模式。 也许其他创作设计模式也适合。

您需要在工厂级别强制执行“singleton-ness”,然后调用可能如下所示:

 FooFactory.GetBarInstance().SomeDerivedMethod(); 

它不是一个真正的答案,但也许很高兴知道。 懒

为什么不简单地将方法声明为非generics并直接使用派生类型:

 public class Derived { Derived instance; public static Derived GetInstance() { if (instance == null) { instance = new Derived(); } return instance; } }