需求: 项目中有很多Manager 类, 每个Manager都需要被单例化 , 同时需要保证项目中其他地方不能实例化Manager,我最开始的写法是在所有的Manager内都进行一次单例化,这样就显得代码重复.
后面想采用泛型单例, 有个问题就是 我仍需要在每个Manager内进行构造函数私有化,下面是我参考的代码
public class Singleton where T : class
{
private static T instance;
private static object initLock = new object();
public static T Instance
{
get
{
if (instance == null)
CreateInstance();
return instance;
}
}
private static void CreateInstance()
{
lock (initLock)
{
if (instance == null)
{
Type t = typeof(T);
// Ensure there are no public constructors...
// 这里确保没有其它的public构造函数了,既没有可以通过其它方法new这个类
ConstructorInfo[] ctors = t.GetConstructors();
if (ctors.Length > 0)
{
throw new InvalidOperationException(String.Format("{0} has at least one accesible ctor making it impossibleto enforce DyhSingleton behaviour", t.Name));
}
instance = (T)Activator.CreateInstance(t, true);
}
}
}
}
现在的需求就是 我想将 构造函数的私有化 放在这个泛型单例的类里面,在子类中可以不用去私有化构造函数了,而且 还有就是 我也能够在子类中去写私有化构造函数,因为我可能会在构造函数中去进行某些操作
|