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; } } }
|
请发表评论