C#面向对象设计模式学习笔记(1) - Singleton 单件模式(创建型模式)
Singleton 单件模式
保证一个类只有一个实例,并提供一个该实例的全局访问点。
核心是如何控制用户使用new对一个类的实力构造器的任意调用。
1、单线程Singleton模式实现
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
public class Singleton
{
//private static Singleton instance = new Singleton(); //不进行延时加载
private static Singleton instance;
private Singleton() { } //构造器
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
public class Test
{
public static void Main()
{
Singleton t1 = Singleton.Instance;
Singleton t2 = Singleton.Instance;
Console.WriteLine(Object.ReferenceEquals(t1, t2) == true);
}
}
2、多线程Singleton模式实现
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
public class Singleton
{
private static volatile Singleton instance = null; //“volatile”用于保证代码执行顺序不被编译器调整
private static object lockHelper = new Object();
private Singleton() { }
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (lockHelper)
{
if (instance == null)
{
instance = new Singleton();
}
}
}
return instance;
}
}
}
3、使用静态构造器实现
特点:多线程、延时加载都能保证,但是不能传参数,如果需要传参数,可以附加属性或方法实现。
实际项目中比较推荐的做法
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
public class Singleton
{
public static readonly Singleton Instance = new Singleton();
private Singleton() { }
}
public class Singleton
{
public static readonly Singleton Instance;
static Singleton()//静态构造器
{
Instance = new Singleton();
}
private Singleton() { }
}