我是靠谱客的博主 幸福洋葱,这篇文章主要介绍笔试Java实现单例设计模式(最优方案),现在分享给大家,希望可以做个参考。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class SingletonTest { private SingletonTest() //构造函数私有化 { } private static class Inner //私有的静态内部类 { static SingletonTest singletonTest = new SingletonTest(); } public static SingletonTest getInstance() { return Inner.singletonTest; } }

因为静态内部类只有在使用的时候才会被Classloader 加载。而JVM 类加载的时候又是线程安全的。


其他实现方法:

最常见(懒汉式)【线程不安全】:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class SingletonTest { private static SingletonTest singletonTest = null; private SingletonTest() { } public static SingletonTest getInstance() { //在类的静态方法中实例化单例 if (null == singletonTest) { singletonTest = new SingletonTest(); } return singletonTest; } }



饿汉式

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class SingletonTest { //在类里面实例化静态成员变量 private static SingletonTest singletonTest = new SingletonTest(); private SingletonTest() { } public static SingletonTest getInstance() { return singletonTest; } }



双重检查锁

复制代码
1
2
3
4
5
6
7
8
9
10
11
public static Singleton getInstance() { if (instance == null) { synchronized(Singleton.class) { if (instance == null) instance = new Singleton(); } } return instance; }

双重检查锁定背后的理论是完美的。不幸地是,现实完全不同。双重检查锁定的问题是:并不能保证它会在单处理器或多处理器计算机上顺利运行。

最后

以上就是幸福洋葱最近收集整理的关于笔试Java实现单例设计模式(最优方案)的全部内容,更多相关笔试Java实现单例设计模式(最优方案)内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(74)

评论列表共有 0 条评论

立即
投稿
返回
顶部