单例模式在使用中可以建立一个单例的泛型。
在其他类型调用的时侯直接在类型的后面加上 NormalSingleton<ConfigSupports>
其他地方使用到ConfigSupports.Instance()调用。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace Nova.LCT.FloorTileScreen
{
/// <summary>
/// 常规单例
/// </summary>
/// <typeparam name="T"></typeparam>
public class NormalSingleton<T> 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, false);
}
else
{
// Create an instance via the private constructor
_instance = (T)Activator.CreateInstance(t, true);
}
}
}
}
}
}