Singleton

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//延迟实例化(多线程)
public class Singleton {
private volatile static Singleton uniqueInstance;
private Singleton() {}
private static Singleton getInstance() {
if (uniqueInstance == null) {
synchronized (Singleton.class) {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}
1
2
3
4
5
6
7
8
9
10
//急切模式
public class Singleton {
private static Singleton uniqueInstance = new Singleton();
private Singleton() {}
private static Singleton getInstance() {
return uniqueInstance;
}
}