我有几个单例类,所以我尝试使用方法 GetInstance(params) 和派生类创建一个父 BaseClass,它们应该实现此方法并返回它们自己的实例(所以我不必强制转换它们)...它们是单例,方法应该是静态的,但不允许覆盖静态方法。编码的最佳方法是什么?我想要的示例代码:
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;
}
}
在这之外的代码中我想调用
Derived.GetInstance().SomeDerivedMethod()
not
(Derived.GetInstance() as Derived).SomeDerivedMethod() and not
new Derived().getInstance().SomeDerivedMethod()
我知道这不好,而且我也缺乏T型的经验,所以欢迎任何建议。
谢谢
EDIT:
或者,如果可以以某种方式在 Base 中定义 GetInstance() 方法,那么派生类不需要覆盖它,但它将返回调用它的类的实例... Derived.GetInstance() 将返回实例派生的
你可以使用Dictionary<Type, Object>
为您的单身人士。下面的方法要求每个类型都实现私有的构造函数。当然,如果单例字典中已经存在该类的实例,您也可以检查每个派生类。这甚至可以避免有人使用Activator
创建一个实例。
未测试:
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;
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)