Java设计模式---单例模式
来源:互联网 发布:最强淘宝系统txt无弹窗 编辑:程序博客网 时间:2024/06/03 22:39
单例模式的几种实现方法,具体如下:
懒汉模式
public class Singleton{ private static Singleton instance; private Singleton(){ } public static Singleton getInstance(){ if(instance == null){ instance = new Singleton(); } return instance; }}
优点
- 可以延迟加载
缺点
- 多线程不安全
饿汉模式
public class Singleton { private static Singleton instance = new Singleton(); private Singleton(){} public static Singleton getInstance(){ return instance; }}
优点
- 多线程安全
缺点
- 加载类时就初始化完成,无法延时加载
双重检查
public class Singleton { private static Singleton instance ; private Singleton(){} public static Singleton getInstance(){ if (instance == null){ synchronized (Singleton.class){ if (instance == null){ instance = new Singleton(); } } } return instance; }}
优点
- 多线程安全
- 延迟加载
缺点
- 同步耗时
静态内部类
public class Singleton { private Singleton(){} public static Singleton getInstance(){ return SingletonHolder.instance; } private static class SingletonHolder { private static Singleton instance = new Singleton(); }}
优点
- 多线程安全
- 延迟加载
- 耗时短(与双重检查相比)
用缓存实现
public class Singleton { private static final String KEY = "instance"; private static Map<String, Singleton> map = new HashMap<>(); private Singleton(){} public static Singleton getInstance(){ Singleton singleton ; if (map.get(KEY) == null){ singleton = new Singleton(); map.put(KEY, singleton); } else { singleton = map.get(KEY); } return singleton; }}
优点
- 线程安全
缺点
- 占用内存较大
枚举模式
public enum Singleton { instance; public void operate(){}}
优点
- 简洁
缺点
- 占用内存大(Android官方不推荐使用枚举)
更多文章请移步我的博客:DevWiki Bolg
0 0
- java 设计模式,单例设计模式
- java设计模式-单例设计模式
- java设计模式-单例设计模式
- Java设计模式 单例设计模式
- Java设计模式------单例设计模式
- java设计模式----->单例设计模式
- java设计模式:单例设计模式
- java设计模式-----单例设计模式
- Java设计模式----单例设计模式
- java设计模式-单例设计模式
- java设计模式:单例设计模式
- java 设计模式-单例设计模式
- Java设计模式--单例设计模式
- java设计模式---单例设计模式
- Java设计模式-单例设计模式
- JAVA设计模式:单例设计模式
- java-单例设计模式
- Java设计|单例模式
- Fragment之onActivityResult
- mysql主从复制 设置中继日志自动清除 主从同步失败,如何快速同步
- mybatis学习笔记(3)-入门程序一
- Demo9:简单晒单效果
- mybatis学习笔记(3)-入门程序二
- Java设计模式---单例模式
- LeetCode88——Merge Sorted Array
- AAC音频格式详解
- BZOJ-3231 递归数列 矩阵连乘+快速幂
- 移动APP的开发技巧(上)
- Bean获取Spring容器
- Android系统下载管理DownloadManager功能介绍及使用示例
- Windows下安装MySQL卡在Starting Server..的解决办法
- 4G(LTE)背后的技术和利益纠结——VoIP,VoLTE,SIP,IMS的前世今生