码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-10-14 23:16:00      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:

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

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; 
}
}

 

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

标签:

原文地址:http://www.cnblogs.com/zscmj/p/5962245.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!