单例模式(Singleton):保证一个类仅有一个实例,并提供一个访问它的全局访问点。
单例模式(单件模式)
使用方法返回唯一的实例
public class SingLeton
{
//创建一个私有的构造函数(必须),堵住外界使用new创建此实例的可能
private SingLeton()
{
}
private static SingLeton instance;
public static SingLeton GetInstance()
{
if (instance ==null )
{
instance = new SingLeton();
}
return instance;
}
}
使用属性返回唯一的实例
public class SingLeton
{
//创建一个私有的构造函数(必须),堵住外界使用new创建此实例的可能
private SingLeton()
{
}
private static SingLeton instance;
public static SingLeton Instance
{
get
{
if (instance==null )
{
instance = new SingLeton();
}
return instance;
}
}
}
多线程访问时需要对实例进行加锁
public class SingLeton
{
//创建一个私有的构造函数(必须),堵住外界使用new创建此实例的可能
private SingLeton()
{
}
private static SingLeton instance;
//定义一个辐助对象
private static object obj = new object();
//多线程使用单例模式(double check 双重检查)
public static SingLeton GetInstances()
{
if (instance ==null )
{
lock (obj) //为实例加锁
{
if (instance ==null)
{
instance = new SingLeton();
}
}
}
return instance;
}
}
在C#与公共语言运行库也提供了一种“静态初始化”方法,这种方法不需要开发人员显式地编写线程安全代码,即可解决多线程环境下它是不安全的问题
public sealed class Singleton
{
//1.使用readonly的方式
private static readonly Singleton instance = new Singleton();
private Singleton()
{
}
public static Singleton GetInstance()
{
return instance;
}
}
由于这种静态初始化方式是自己被加载时就将自己实例化,所以被形象地称之为饿汉式单例类,上面两种处理方式是要在第一次被引用时,才会将自己实例化,所以就被称为懒汉式单例类。
由于饿汉式,即静态初始化方式,是类一加载就实例化,所以要提前占用系统资源,然而懒汉式,又会面临多线程访问安全性的问题,需要双重锁定的处理才可以保证安全。所在到底使用哪一种方式,取决于实际的需求。