要注意的都加注释了
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35package test; /** * @Author 小浩 * @Date 2020/4/12 15:36 * @Version 1.0 **/ public class Singleton { // volatile 防止指令重排序 new对象不是原子操作 private static volatile Singleton singleton; // 判断是否已经存在 防止反射修改构造方法为public private Singleton() { if (singleton != null) { try { throw new Exception("非法访问"); } catch (Exception e) { e.printStackTrace(); } } } public static Singleton getInstance() { // synchronized 不放在方法上提高效率 这样只在对象没生成的时候加锁 // 双重检测第二个检测是因为 有可能同时多个线程走进第一个if里边 再次判断可防止重复new对象 if (singleton == null) { synchronized (Singleton.class) { if (singleton == null) { singleton = new Singleton(); } } } return singleton; } }
测试类:
通过反射修改构造方法为public 并且new对象发现抛异常,这是因为我们对非法访问进行了限制
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26package test; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; public class Test { public static void main(String[] args) { Singleton instance = Singleton.getInstance(); Class singletonClass = Singleton.class; Constructor[] declaredConstructors = singletonClass.getDeclaredConstructors(); declaredConstructors[0].setAccessible(true); try { declaredConstructors[0].newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } }
输出结果:
最后
以上就是开放雪碧最近收集整理的关于单例模式懒汉式Java版的全部内容,更多相关单例模式懒汉式Java版内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复