C# 的static与单例模式

C# 的static与单例模式

static是静态对象,在类被第一次使用,或者第一次被实例化时执行

/// <summary>
/// 线程安全的单件模式
/// </summary>
public sealed class StaticCustomer
{
private static volatile IList<Customer> instance = null;
// Lock对象,线程安全所用
private static object syncRoot = new Object();

private StaticCustomer() { }

public static IList<Customer> Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new LinqDBDataContext().Customer.ToList();
}
}

return instance;
}
}
}

/// <summary>
/// 简单的模式,没有考虑线程问题
/// </summary>
public sealed class SingtonCustomer
{
private static IList<Customer> instance = null;
private SingtonCustomer() { }
public static IList<Customer> Instance
{
get
{
if (instance == null)
{
instance = new LinqDBDataContext().Customer.ToList();
}
return instance;
}
}
}

posted @ 2016-06-27 15:29  那就让我这样吧  阅读(1220)  评论(0编辑  收藏  举报