单例模式的基本运用
来源:互联网 发布:阿里云开启3306端口 编辑:程序博客网 时间:2024/05/16 11:54
单例模式
饿汉式
public class Singleton { private static final Singleton INSTANCE = new Singleton(); private Singleton(){ } public static Singleton getInstance(){ return INSTANCE; } }
饿汉式,提前开辟了内存空间,资源浪费。
懒汉式
public class Singleton { private static Singleton instance; private Singleton(){ } public static synchronized Singleton getInstance(){ if(instance == null){ instance = new Singleton(); } return instance; } }
懒汉式只有需要的时候才加载。性能差。
DCL模式
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; } }
DCL模式资源利用率高,第一次执行方法是单例对象才会被实例化,第一次加载时会稍慢;
静态内部类实现单例模式
public class Singleton { private static Singleton instance; private Singleton() { } public static class SingletonInstance { private static final Singleton INSTANCE = new Singleton(); } public static Singleton getInstance() { return SingletonInstance.INSTANCE; } }
线程安全,且懒加载。
因为是静态内部类,所以要在有引用了以后才会装载到内存的,所以是懒加载。
线程安全,是因为类加载过程是安全的。
阅读全文
0 0
- 单例模式的基本运用
- 单例模式和NSOperation的运用
- 单例模式和中介者模式的运用
- 策略模式的基本运用
- 观察者模式的基本运用
- C++ 单例模式析构函数的运用
- [转]C++ 单例模式析构函数的运用
- C++ 单例模式析构函数的运用
- Android 中运用单例模式的方法说明
- android 的getInstance运用(单例模式)
- cocos2d-x中的单例模式运用
- cocos2d-x中的单例模式运用
- cocos2d-x中的单例模式运用
- Cocos2d-x入门:单例模式运用
- 单例模式在游戏中的运用
- 单例模式对比,运用,总结
- java 单例模式及运用
- 单例运用的范围
- Oracle 11g安装与卸载
- sql sever客户端连接的问题
- 连接数据库错误
- Web前端开发最佳实践总结三:CSS最佳实践
- 椒盐噪声的图片 利用中值滤波效果好
- 单例模式的基本运用
- 设计模式之观察者模式
- NOI模拟(10.29)T3 颜色
- [地图]仿射变换矩阵
- maven创建eclipse工程
- 2017.10.30
- Django Admin管理工具
- centos7 javaweb 链接中文请求tomcat乱码问题解决
- LeetCode110. Balanced Binary Tree