Singleton设计模式 分类: 设计模式 2014-12-03 17:54 59人阅读 评论(0) 收藏
实现方法:
public class SingleTon<T> where T : class, new()
{
protected SingleTon() { }
private static T _instance;
private static readonly object _syncRoot = new object();
public static T Instance
{
get
{
if (_instance == null)
{
lock (_syncRoot)
{
//Double-Check双重检查锁定,对于多线程访问时控制
if (_instance == null)
{
_instance = new T();
}
}
}
return _instance;
}
}
}使用方法:
public class BusinessManager : SingleTon<BusinessManager>
{
public void SayHello()
{
Console.WriteLine("Hello");
}
}方法调用:
BusinessManager.Instance.SayHello();
版权声明:本文为博主原创文章,未经博主允许不得转载。

浙公网安备 33010602011771号