单例(singleton)模式
来源:互联网 发布:java编程技巧 编辑:程序博客网 时间:2024/06/14 04:03
1.意图
确保一个类只有一个实例,并提供一个全局访问点。
2.解释
- 确保只创建一个特定类的一个对象。
- 在软件工程中,单例模式是将类的实例化限制为一个对象的软件设计模式。当需要一个对象来协调整个系统的动作时,这是非常有用的。
3.使用场景
- 必须只有一个类的一个实例,并且必须可以从一个众所周知的接入点访问客户端。
- 当唯一的实例应该通过子类化可扩展,并且客户端应该能够使用扩展实例而不修改它们的代码。
4.单例的几种形式
1.饿汉模式
public class IvoryTower { private IvoryTower() { } private static final IvoryTower INSTANCE = new IvoryTower(); public static IvoryTower getInstance() { return INSTANCE; }}
2.懒汉模式
public class InitializingOnDemandHolderIdiom { private InitializingOnDemandHolderIdiom() { } public static InitializingOnDemandHolderIdiom getInstance() { return HelperHolder.INSTANCE; } private static class HelperHolder { private static final InitializingOnDemandHolderIdiom INSTANCE = new InitializingOnDemandHolderIdiom(); }}
3.懒汉模式(线程安全)
public class ThreadSafeLazyLoadedIvoryTower { private static ThreadSafeLazyLoadedIvoryTower instance; private ThreadSafeLazyLoadedIvoryTower() { if (instance != null) { throw new IllegalStateException("Already initialized."); } } public static ThreadSafeLazyLoadedIvoryTower getInstance() { if (instance == null) { instance = new ThreadSafeLazyLoadedIvoryTower(); } return instance; }}
4.懒汉模式(线程安全双检测)
public class ThreadSafeDoubleCheckLocking { private static volatile ThreadSafeDoubleCheckLocking instance; private ThreadSafeDoubleCheckLocking() { if (instance != null) { throw new IllegalStateException("Already initialized."); } } public static ThreadSafeDoubleCheckLocking getInstance() { ThreadSafeDoubleCheckLocking result = instance; if (result == null) { synchronized (ThreadSafeDoubleCheckLocking.class) { result = instance; if (result == null) { instance = result = new ThreadSafeDoubleCheckLocking(); } } } return result; }}
参考教程:https://github.com/iluwatar/java-design-patterns/tree/master/singleton
阅读全文
0 0
- 单例模式(singleton)
- 单例(Singleton)模式
- 单例模式(Singleton)
- 单例模式(Singleton)
- Singleton(单例)模式
- 单例模式(Singleton)
- 单例模式(Singleton)
- 单例模式(Singleton)
- 单例模式(singleton)
- 单例模式(Singleton)
- 单例模式(Singleton)
- 单例模式(Singleton)
- 单例模式(Singleton)
- 单例(Singleton)模式
- 单例(Singleton)模式
- 单例(Singleton)模式
- 单例模式(Singleton)
- Singleton(单例模式)
- C++中的const,引用,和指针
- 解决Linux开机进入Initramfs无法开机
- Median of Two Sorted Arrays
- PHP JavaScript横向总结、对比(判断、循环)
- C#基础1_.net介绍及平台基础
- 单例(singleton)模式
- 64位windows7下使用CopyFile()函数复制文件到系统目录下不成功问题
- C/C++题库整理(二)
- linux下的平台总线与专用总线
- C++实验18
- js冒泡排序
- 图像压缩变换
- nginx负载均衡之加权轮询
- ^KeepTool.v9.0.3.1.Incl.Keygen-BLiZZARD\