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

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

最新文章

  1. 关于absolute 和 relative 定位的定义
  2. JMeter学习-020-JMeter 监听器之【聚合报告】错误率、吞吐量、传输速率实例计算
  3. IEnumerable和IEnumerator 详解 (转)
  4. android开发时,finish()跟System.exit(0)的区别
  5. wdate-year-month-week-gategory-amount-coin
  6. shell脚本实例-游戏脚本
  7. 【Android - 基础】之Dialog分类及使用
  8. Arcgis for Js之Graphiclayer扩展具体解释
  9. Java数据结构和算法 - 链表
  10. Elasticsearch系列(4):基本搜索
  11. Win10外包公司(长年承接Win10App外包、Win10通用应用外包)
  12. onkeyup+onafterpaste 只能输入数字和小数点--转载
  13. HBase读写数据的详细流程及ROOT表/META表介绍
  14. Split()[1]中的[1]是什么意思
  15. SSM 开发 Tars
  16. EF基础知识小记二
  17. spring mvc 如何传递集合参数(list,数组)
  18. C#中的异步调用及异步设计模式(二)——基于 IAsyncResult 的异步设计模式
  19. 35 个你也许不知道的 Google 开源项目
  20. git克隆出错 github clone Permission denied (publickey) fatal Could not read from remote repo

热门文章

  1. vue安装
  2. MediaWiki使用指南
  3. atitit.数据验证--db数据库数据验证约束
  4. 【Leafletjs】6.Control.Loading推展-在地图上边框添加加载动态条
  5. Android 中的Json解析工具fastjson 、序列化、反序列化
  6. Loader加载器
  7. IOS开发之多线程 -- GCD的方方面面
  8. c#.net 使用NPOI导入导出标准Excel (asp.net winform csharp)
  9. 自定义可视化调试工具(Microsoft.VisualStudio.DebuggerVisualizers)vs.net开发工具
  10. 从多个XML文档中读取数据用于显示webapi帮助文档