单例模式的几种套路

套路1 - 立即加载 instantly initialization

1
2
3
4
5
6
7
8
9
10
11
public class EagerSingleton {
**private** **static** EagerSingleton instance = new EagerSingleton();
**private** EagerSingleton() {
}
public static EagerSingleton getInstance() {
return instance;
}
}

套路2 - 延迟初始化 lazy initialization

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class LazySingleton {
private static LazySingleton instance;
private LazySingleton() {
}
public static **synchronized** LazySingleton getInstance() {
if (instance == null) {
try {
Thread.sleep(1000 * 3);// mock long time init
} catch (InterruptedException e) {
e.printStackTrace();
}
instance = new LazySingleton();
}
return instance;
}
}

套路3 - 静态内部类 static Holder

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class InnerHolderClass {
private InnerHolderClass() {
}
private static class InnerHolder {
static InnerHolderClass innerHolder = new InnerHolderClass();
}
public static InnerHolderClass getInstance() {
InnerHolderClass innerHolder = InnerHolder.innerHolder;
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return innerHolder;
}
}

套路4 - 枚举 enum

1
2
3
public enum EnumSingleton {
SINGLE;
}

套路5 - 双重锁 double check

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class DoubleCheckSingleton {
//volatile is important!!!
//volatile is important!!!
//volatile is important!!!
private static **volatile** DoubleCheckSingleton instance;//volatile is important!!!
private DoubleCheckSingleton() {
}
public static DoubleCheckSingleton getInstance() {
if (null == instance) {
synchronized (DoubleCheckSingleton.class) {
if (null == instance) {
instance = new DoubleCheckSingleton();
}
}
}
return instance;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class EnhancedDoubleCheckSingleton {
private static EnhancedDoubleCheckSingleton instance;
private EnhancedDoubleCheckSingleton() {
}
//it's not the recommend way.we recommend lazy initialization inner class because the static instance field.
public static EnhancedDoubleCheckSingleton getInstance() {
**EnhancedDoubleCheckSingleton tmp = instance;**
if (null == tmp) {
synchronized (EnhancedDoubleCheckSingleton.class) {
**tmp = instance;**
if (null == tmp) {
instance = tmp = new EnhancedDoubleCheckSingleton();
}
}
}
return tmp;
}
}