简体   繁体   English

返回后代的单例实例

[英]Return singleton instances of descendants

I have a couple of classes that are singletons so I tried to create a parent BaseClass with method GetInstance(params) and derived classes, that should implement this method and return instances of theiselfs (so I dont have to cast them)... as they are singletons the method should be static, but its not allowed to override static methods. 我有几个单例类,所以我尝试用方法GetInstance(params)和派生类创建一个父BaseClass,它应该实现这个方法并返回自己的实例(所以我不必抛出它们)... as它们是单例,方法应该是静态的,但不允许覆盖静态方法。 What would be the best approach to code it? 编码它的最佳方法是什么? sample code what i wanted: 我想要的示例代码:

  public class Base {

    public static virtual T GetInstance<T>() where T : class;
  }


  public class Derived {
    Derived instance;

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

in the code outside of this i want to call 在我想要打电话的外面的代码中

Derived.GetInstance().SomeDerivedMethod()

not

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

I know this is not good, and i have lack of experience with the T type too, so any advices are welcomed. 我知道这不好,我也缺乏T型经验,所以欢迎任何建议。 thanks 谢谢

EDIT: 编辑:

Or if it is possible somehow define the GetInstance() method in Base, so the derived class does not need to ovwerride it, but it will return the instance of class from where it was called... Derived.GetInstance() will return instance of Derived 或者,如果有可能以某种方式在Base中定义GetInstance()方法,那么派生类不需要对其进行ovwerride,但它将从调用它的位置返回类的实例... Derived.GetInstance()将返回实例衍生的

Try the Abstract Factory design pattern. 尝试抽象工厂设计模式。 Maybe other creational design patterns may fit too. 也许其他创作设计模式也适合。

You need to enforce the "singleton-ness" on factory level, and then the call may look like: 您需要在工厂级别强制执行“singleton-ness”,然后调用可能如下所示:

FooFactory.GetBarInstance().SomeDerivedMethod();

You could use a Dictionary<Type, Object> for your singletones. 您可以为单个Dictionary<Type, Object>使用Dictionary<Type, Object> The method below requires each type to implement the constructor private. 下面的方法要求每种类型都实现构造函数private。 Of course you could also make a check in each of the derived classes if there is already a instance of the class in the singletones dictionary. 当然,如果单例字典中已经存在该类的实例,您还可以检查每个派生类。 This would even avoid somebody to use the Activator to create a instance. 这甚至可以避免某人使用Activator来创建实例。

Not tested: 未经测试:

public class Base {
    static Dictionary<Type, Object> _Singletones = new Dictionary<Type, Object>();
    public static T GetInstance<T>() 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;
        }
    }
}

its not an real answer but maybe its nice to know anyway. 它不是一个真正的答案,但也许很高兴知道。 Lazy

Why not simply declare the method as non-generic and use the derived type directly: 为什么不简单地将该方法声明为非泛型并直接使用派生类型:

public class Derived {
  Derived instance;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM