单例模式的代码实现
1.懒汉式代码实现:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15public class Singleton { //默认不会实例化,什么时候用就什么时候new private static Singleton instance = null; private Singleton(){ } public static synchronized Singleton getInstance(){ if(instance == null){ //什么时候用就什么时候new instance = new Singleton(); } return instance; } }
2.饿汉式代码实现:
复制代码
1
2
3
4
5
6
7
8
9
10
11public class Singleton { //一开始类加载的时候就实例化,创建单实例对象 private static Singleton instance = new Singleton(); private Singleton(){ } public static Singleton getInstance(){ return instance; } }
二者的区别:
1.线程安全性
饿汉式在线程还没出现之前就已经实例化了,所以饿汉式一定是线程安全的。懒汉式加载是在使用时才会去new 实例的,那么你去new的时候是一个动态的过程,是放到方法中实现的
2.效率
效率与线程安全性一般成正比
饿汉式没有加任何的锁,因此执行效率比较高。懒汉式一般使用都会加同步锁,效率比饿汉式差。
3.开销
饿汉式在一开始类加载的时候就实例化,无论使用与否,都会实例化,所以会占据空间,浪费内存。懒汉式什么时候用就什么时候实例化,不浪费内存
最后
以上就是机智草丛最近收集整理的关于单例模式中懒汉式和饿汉式实现的全部内容,更多相关单例模式中懒汉式和饿汉式实现内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复