【2016-10-14】【坚持学习】【Day5】【单例模式】
2024-08-31 06:47:12
今天学习第二个模式:单例模式。只允许系统有一个实例运行,提供全局访问该实例的公共方法。
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;
}
}
最新文章
- 关于absolute 和 relative 定位的定义
- JMeter学习-020-JMeter 监听器之【聚合报告】错误率、吞吐量、传输速率实例计算
- IEnumerable和IEnumerator 详解 (转)
- android开发时,finish()跟System.exit(0)的区别
- wdate-year-month-week-gategory-amount-coin
- shell脚本实例-游戏脚本
- 【Android - 基础】之Dialog分类及使用
- Arcgis for Js之Graphiclayer扩展具体解释
- Java数据结构和算法 - 链表
- Elasticsearch系列(4):基本搜索
- Win10外包公司(长年承接Win10App外包、Win10通用应用外包)
- onkeyup+onafterpaste 只能输入数字和小数点--转载
- HBase读写数据的详细流程及ROOT表/META表介绍
- Split()[1]中的[1]是什么意思
- SSM 开发 Tars
- EF基础知识小记二
- spring mvc 如何传递集合参数(list,数组)
- C#中的异步调用及异步设计模式(二)——基于 IAsyncResult 的异步设计模式
- 35 个你也许不知道的 Google 开源项目
- git克隆出错 github clone Permission denied (publickey) fatal Could not read from remote repo
热门文章
- vue安装
- MediaWiki使用指南
- atitit.数据验证--db数据库数据验证约束
- 【Leafletjs】6.Control.Loading推展-在地图上边框添加加载动态条
- Android 中的Json解析工具fastjson 、序列化、反序列化
- Loader加载器
- IOS开发之多线程 -- GCD的方方面面
- c#.net 使用NPOI导入导出标准Excel (asp.net winform csharp)
- 自定义可视化调试工具(Microsoft.VisualStudio.DebuggerVisualizers)vs.net开发工具
- 从多个XML文档中读取数据用于显示webapi帮助文档