1 package com.java.singleton;
2
3 /**
4 * 单例模式
5 *
6 */
7 public class SingletonTest {
8
9 public static void main(String[] args) {
10 Singleton7 instance1 = Singleton7.getInstance();
11 Singleton7 instance2 = Singleton7.getInstance();
12
13 System.out.println(instance1 == instance2);
14 }
15
16 }
17
18 /**
19 * 饿汉式
20 * 对象随着类的加载被创建,类只加载一次,因此饿汉式无多线程安全问题
21 * 缺点:若某个实例不被使用,有点浪费资源
22 */
23 enum Singleton1 {
24 INSTANCE;
25 }
26
27 class Singleton2 {
28 public static final Singleton2 INSTANCE = new Singleton2();
29 }
30
31 class Singleton3 {
32 private static final Singleton3 INSTANCE = new Singleton3();
33
34 private Singleton3() {
35
36 }
37
38 public static Singleton3 getInstance() {
39 return INSTANCE;
40 }
41 }
42
43 /**
44 * 懒汉式
45 * 不考虑多线程安全问题
46 */
47 class Singleton4 {
48 private static Singleton4 instance = null;
49
50 private Singleton4() {
51
52 }
53
54 public static Singleton4 getInstance() {
55 if (instance == null) {
56 instance = new Singleton4();
57 }
58
59 return instance;
60 }
61 }
62
63 /**
64 * 懒汉式需要考虑多线程安全问题
65 * 缺点:每次调用方法,都需要先判断锁的操作,因此效率低,不建议使用
66 */
67 class Singleton5 {
68 private static Singleton5 instance = null;
69
70 private Singleton5() {
71
72 }
73
74 public static synchronized Singleton5 getInstance() {// Singleton5.class
75 if (instance == null) {
76 instance = new Singleton5();
77 }
78
79 return instance;
80 }
81 }
82
83 /**
84 * 懒汉式,虽然第一次多判断了一个if,但是后续的线程不需要每次都判断锁的操作,因此效率略高,建议使用
85 */
86 class Singleton6 {
87 private static Singleton6 instance = null;
88
89 private Singleton6() {
90
91 }
92
93 public static Singleton6 getInstance() {
94 if (instance == null) {
95 synchronized (Singleton6.class) {
96 if (instance == null) {
97 instance = new Singleton6();
98 }
99 }
100 }
101
102 return instance;
103 }
104 }
105
106 /**
107 * 静态内部类:该方式,外部类被加载,内部类中对象不会被创建,也可实现延迟加载,因此建议使用
108 */
109 class Singleton7 {
110
111 private static class InnerClass {
112 private static final Singleton7 INSTANCE = new Singleton7();
113 }
114
115 public static Singleton7 getInstance() {
116 return InnerClass.INSTANCE;
117 }
118 }