返回后代单实例 [英] Return singleton instances of descendants

查看:171
本文介绍了返回后代单实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个是单身类,所以我试图创建方法getInstance(PARAMS)和派生类父BaseClass的,应该实现此方法,并返回theiselfs的实例(所以我没有投他们)。 ..因为它们是单件的方法应该是静态的,但其不能重写的静态方法。什么是最好的方法的代码呢?示例代码我想要的:

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. 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()

不是

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

我知道这是不好,我有缺乏与T类型过于经验,因此任何建议都欢迎。
感谢

I know this is not good, and i have lack of experience with the T type too, so any advices are welcomed. thanks

编辑:

或者是否有可能以某种方式定义相应getInstance()方法,因此派生类并不需要ovwerride它,但它会返回类从那里它被称为实例... Derived.GetInstance()返回的Derived实例

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

推荐答案

您可以使用词典<类型,对象> 为您singletones。下面的方法要求每个类型实现构造私有的。当然,你也可以使每个派生类的检查,如果已经有在singletones字典类的实例。这甚至会避免有人使用激活来创建一个实例

You could use a Dictionary<Type, Object> for your singletones. The method below requires each type to implement the constructor 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.

未测试:

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;
        }
    }
}

这篇关于返回后代单实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆