简介:
单例是一个只允许创建自身的单个实例的类。单例模式是软件工程中最着名的模式之一。
介绍:

优点 | 单一实例。 |
缺点 | 不支持带参构造函数。 |
特点 | 私有无参的构造函数,类不可继承,只有一个公共静态实例。 |
使用:
1.单线程安全
- 通过方法或属性返回实例。
- 多线程不安全,不建议使用。
public sealed class Singleton
{
//静态声明
private static Singleton singleton;
//防止外界创建
private Singleton()
{
}
//返回唯一实例
public static Singleton GetInstance()
{
if (singleton == null)
{
singleton = new Singleton();
}
return singleton;
}
}
public sealed class Singleton
{
private static Singleton singleton;
private Singleton()
{
}
public static Singleton Instance
{
get
{
if (singleton == null)
{
singleton = new Singleton();
}
return singleton;
}
}
}
2.多线程安全
2.1 简单线程安全
public sealed class Singleton
{
private static volatile Singleton singleton;
private static readonly object obj = new object();
private Singleton()
{
}
public static Singleton GetInstance()
{
lock (obj)
{
if (singleton == null)
{
singleton = new Singleton();
}
}
return singleton;
}
}
2.2 双重检查锁定
public sealed class Singleton
{
private static volatile Singleton singleton;
private static readonly object obj = new object();
private Singleton()
{
}
public static Singleton GetInstance()
{
if (singleton == null)
{
lock (obj)
{
if (singleton == null)
{
singleton = new Singleton();
}
}
}
return singleton;
}
}
3.饿汉式
public sealed class Singleton
{
public static readonly Singleton instance = new Singleton();
private Singleton()
{
}
}
public sealed class Singleton
{
public static readonly Singleton instance;
private Singleton()
{
}
static Singleton()
{
instance = new Singleton();
}
}
4.Lazy<T>
Lazy< T> 类的所有公共和受保护的成员都是线程安全的,可从多个线程同时使用。可根据需要以及按实例删除这些线程安全保证,使用该类型的构造函数的参数。
Lazy< T> (LazyThreadSafetyMode) | 初始化 Lazy< T> 类的新实例,其中使用T 的默认构造函数和指定的线程安全性模式。 |
名称 | 说明 |
---|---|
IsValueCreated | 获取一个值,该值指示是否已为此 Lazy< T> 实例创建一个值。 |
Value | 获取当前 Lazy< T> 实例的延迟初始化值。 |
public sealed class Singleton
{
private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance
{
get
{
return lazy.Value;
}
}
private Singleton()
{
}
}