单例模式
来源:互联网 发布:php 设置头部 编辑:程序博客网 时间:2024/06/18 04:39
单例模式:确保一个类只有一个实例,并提供一个全局访问点。
下面我们介绍几种常见的实现方式。
1. 饿汉式:线程安全
public class Singleton { private static Singleton instance = new Singleton(); private Singleton() {} public static Singleton getInstance(){ return instance; }}
2. 懒汉式:非线程安全
public class Singleton { private static Singleton instance = null; private Singleton() {} public static Singleton getInstance(){ if(instance == null){ instance = new Singleton(); } return instance; }}
3. 使用synchronized:线程安全
public class Singleton { private static Singleton instance = null; private Singleton() {} public static synchronized Singleton getInstance(){ if(instance == null){ instance = new Singleton(); } return instance; }}
4. 双重检查加锁:线程安全
public class Singleton { private volatile static Singleton instance = null; private Singleton() {} public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; }}
阅读全文
0 0
- 单例、单例模式
- 单例模式-多线程单例模式
- 单件模式(单例模式)
- 设计模式------单例模式
- 设计模式------单例模式
- 设计模式-单例模式
- 设计模式 - 单例模式
- 设计模式---单例模式
- 设计模式---单例模式
- PHP模式-单例模式
- 【设计模式】单例模式
- 设计模式-单例模式
- 设计模式----单例模式
- 设计模式--单例模式
- 设计模式-单例模式
- 单例模式(单子模式)
- 设计模式-单例模式
- [设计模式] 单例模式
- SAP FIORI教程——如何设置Launchpad的多语言文件(SAP Cloud 版)
- 处理数字--cookbook读书笔记
- python图像处理库Pillow入门(一)
- 单点登录(SSO)
- Vmware虚拟机三种网络模式详解
- 单例模式
- BZOJ2006 [NOI2010] ST表 + 堆
- Linux bash 编程
- HTTP协议
- usb协议包概述
- 15个最受欢迎的Python开源框架
- 常见排序算法总结
- python列表推导式
- 注意!!变量在变化!!