最理想的非泛型实现:
/// <summary>
/// 单例模式的实现
/// </summary>
public class Singleton
{
// 定义一个静态变量来保存类的实例
private static Singleton uniqueInstance;
// 定义一个标识确保线程同步
private static readonly object locker = new object();
// 定义私有构造函数,使外界不能创建该类实例
private Singleton()
{
}
/// <summary>
/// 定义公有方法提供一个全局访问点,同时你也可以定义公有属性来提供全局访问点
/// </summary>
/// <returns></returns>
public static Singleton GetInstance()
{
// 当第一个线程运行到这里时,此时会对locker对象 "加锁",
// 当第二个线程运行该方法时,首先检测到locker对象为"加锁"状态,该线程就会挂起等待第一个线程解锁
// lock语句运行完之后(即线程运行完之后)会对该对象"解锁"
if(uniqueInstance ==null){ //双层if将性能开销降到最低
lock (locker)
{
// 如果类的实例不存在则创建,否则直接返回
if (uniqueInstance == null)
{
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}
/// <summary>
/// 单例模式泛型类
/// </summary>
/// <typeparam name="T">类</typeparam>
public abstract class Singleton<T> where T : class
{
private static T _Instance;
private static readonly object Locker = new object();
public static T GetInstance()
{
if (_Instance == null)
{
lock (Locker)
{
if (_Instance == null)
{
_Instance = (T) Activator.CreateInstance(typeof(T), true);
}
}
}
return _Instance;
}
}
调用:
public class MySingleton : Singleton<MySingleton>
{
public void IncrementCounter()
{
Console.WriteLine(11111111111111);
}
}
static void Main(string[] args)
{
for (int j = 0; j < 1000; ++j)
MySingleton.GetInstance().IncrementCounter();
Console.ReadLine();
}
以上泛型可以是where T:new() , 但是实现类必须得是共有的构造函数
当然也可以用lazy
public abstract class Singleton<T> where T : class
{
private static Lazy<T> _instance = new Lazy<T>(() => (T)Activator.CreateInstance(typeof(T), true));
public static T Instance
{
get
{
return _instance.Value;
}
}
}