【2016-10-14】【坚持学习】【Day5】【单例模式】

今天学习第二个模式:单例模式。只允许系统有一个实例运行,提供全局访问该实例的公共方法。

class Singleton 
{
    private static Singleton instance=null;  //静态私有成员变量

    //私有构造函数
    private Singleton()
    {    
    }
    
    //静态公有工厂方法,返回唯一实例
    public static Singleton GetInstance() 
    {
        if(instance==null)
            instance=new Singleton();    
        return instance;
    }
}

 

饿汉单例:

class EagerSingleton 
{ 
private static EagerSingleton instance = new EagerSingleton(); 
private EagerSingleton() { } 
public static EagerSingleton GetInstance() 
{
return instance; 
}
}

懒汉单例+双重保险

class LazySingleton 
{ 
private static LazySingleton instance = null; 
//程序运行时创建一个静态只读的辅助对象
private static readonly object syncRoot = new object();
private LazySingleton() { } 
public static LazySingleton GetInstance() 
{ 
      //第一重判断,先判断实例是否存在,不存在再加锁处理
if (instance == null) 
{
    //加锁的程序在某一时刻只允许一个线程访问
lock(syncRoot)
{
    //第二重判断
    if(instance==null)
    {
        instance = new LazySingleton();  //创建单例实例
}
}
}
return instance; 
}
}

 

posted @ 2016-10-14 21:56  zscmj  阅读(199)  评论(0编辑  收藏  举报