保证一个类仅有一个实例,,并提供一个访问它的全局访问点
//懒汉式
class Singleton
{
private static Singleton instance;
private Singleton()
{}
public static Singleton GetInstance()
{
if (NULL == instance)
{
instance = new Singleton();
}
return instance;
}
};
多线程时的单例模式:
//多线程情况下:
class Singleton
{
private static Singleton instance;
//加一个锁
private static readonly object sync = new object();
private Singleton()
{}
public static Singleton GetInstance()
{
if (NULL == instance) //先判断是否存在,不存在再竞争
//之所以要这样,是为了防止每次调用都要涉及到锁,毕竟只实例化一次
{
lock(sync)
{
if (NULL == instance)
{
instance = new Singleton();
}
}
}
return instance;
}
};
单例模式分两类
一、在自己被加载时就将自己实例化,称为饿汉式单例类
类一加载就实例化对象,提前占用系统资源
//饿汉式
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton()
{}
public static Singleton GetInstance()
{
return instance;
}
};
二、在第一次被引用时才将自己实例化,称为懒汉式单例类
面临多线程访问的安全性问题, 即第一个程序那样