【设计模式】单例模式
来源:互联网 发布:java分页怎么实现 编辑:程序博客网 时间:2024/05/02 03:10
单例模式
单例模式是设计模式中比较简单的一种设计模式。
有许多种写法:
第一种 不考虑线程安全
/// <summary> /// First version - not thread-safe /// </summary> public sealed class Singleton { /// <summary> /// 静态 /// </summary> static Singleton instance = null; /// <summary> /// 私有构造函数 /// </summary> Singleton() { } /// <summary> /// public property /// </summary> public static Singleton Instance { get { if (instance == null) { instance = new Singleton(); } return instance; } } }
第二种 线程安全
/// <summary> /// Second version - simple thread-safety /// </summary> public sealed class Singleton { static Singleton instance = null; /// <summary> /// /// </summary> static readonly object padlock = new object(); Singleton() { } public static Singleton Instance { get { lock (padlock) { if (instance == null) { instance = new Singleton(); } return instance; } } } }
第三种 我没看懂
/// <summary> /// Third version - attempted thread-safety using double-check locking /// </summary> public sealed class Singleton { static Singleton instance = null; /// <summary> /// /// </summary> static readonly object padlock = new object(); Singleton() { } public static Singleton Instance { get { if (instance == null) { lock (padlock) { if (instance == null) { instance = new Singleton(); } return instance; } } return instance; } } }
第四种 比较偷懒的写法
/// <summary> /// Fourth version - not quite as lazy, but thread-safe without using locks /// </summary> public sealed class Singleton { static readonly Singleton instance = new Singleton(); /// <summary> /// static constructor /// </summary> static Singleton() { } public static Singleton Instance { get { return instance; } } }
第五种 比较偷懒的写法
/// <summary> /// Fifth version - fully lazy instantiation /// </summary> public sealed class Singleton { Singleton() { } public static Singleton Instance { get { return Nested.instance; } } class Nested { // Explicit static constructor to tell C# compiler // not to mark type as beforefieldinit static Nested() { } internal static readonly Singleton instance = new Singleton(); } }
参考文章
Depth in C About Singleton
0 0
- 设计模式------单例模式
- 设计模式------单例模式
- 设计模式-单例模式
- 设计模式 - 单例模式
- 设计模式---单例模式
- 设计模式---单例模式
- 【设计模式】单例模式
- 设计模式-单例模式
- 设计模式----单例模式
- 设计模式--单例模式
- 设计模式-单例模式
- 设计模式-单例模式
- [设计模式] 单例模式
- 设计模式--单例模式
- 设计模式---单例模式
- 设计模式--单例模式
- 设计模式 -----单例模式
- 设计模式:单例模式
- Oracle之物化视图
- SDAutoLayout的使用
- 简单下拉框选项回显
- 第94课:Hive性能调优之Mapper和Reducer设置、队列设置和并行执行、JVM重用和动态分区、Join调优等
- android地区三级联动选择
- 【设计模式】单例模式
- easyui datagird自定义编辑器textbox带按钮
- 【操作系统】连续分配存储管理方式
- 运行 openfire4.04 ServerStarter 报异常 AdminConsolePlugin:192 - An exception occurred while trying to mak
- Linux下的有用命令
- Vivado FIR core修改系数
- java-加密字符串
- DNS查询与BIND名字服务器的一些简单配置文件说明
- PL/SQL导出、导入表数据【实例】