/// <summary>
/// 线程安全的单例模式窗口,支持带参数构造和用户控件
/// 支持任意构造函数的双锁单例模式
/// </summary>
public class SinglFromSafe<T> where T : ContainerControl
{
//volatile 禁用指令重排
private volatile static T t = null;
private static readonly object lockHelper = new object();
public static T CreateInstance(params object[] args)
{
if (t == null || t.IsDisposed)
{
lock (lockHelper)
{
if (t == null||t.IsDisposed)
{
//t = (T)Activator.CreateInstance(typeof(T), args);
// MemoryBarrier,防止多CPU时指令重新排序导致,确保实例对象被良好地初始化,然后才分配给静态变量
var element = (T)Activator.CreateInstance(typeof(T), args);
// ensures that the instance is well initialized, and only then, it assigns the static variable.
System.Threading.Thread.MemoryBarrier();
t = element;
}
}
}
return t;
}
}
/// <summary>
/// 单例模式
/// 静态构造函数
/// </summary>
public sealed class SingleMode
{
//单例模式(私有构造函数)
private SingleMode() { }
private static readonly SingleMode singleInstance = new SingleMode();
public static SingleMode GetInstance
{
get
{
return singleInstance;
}
}
}
/// <summary>
/// 单例模式
/// Lazy延迟初始化
/// </summary>
public sealed class SinglFrom
{
private static readonly Lazy<SinglFrom> lazy = new Lazy<SinglFrom>(() => new SinglFrom());
public static SinglFrom Instance { get { return lazy.Value; } }
private SinglFrom()
{
}
}
/// <summary>
/// 线程安全的单例模式
/// </summary>
public class Singleton
{
private volatile static Singleton _instance = null;
private static readonly object lockHelper = new object();
private Singleton() { }
public static Singleton CreateInstance()
{
if (_instance == null)
{
lock (lockHelper)
{
if (_instance == null)
_instance = new Singleton();
}
}
return _instance;
}
}
常见的单例模式和带参数构造单例
于 2023-10-07 16:32:10 首次发布