单例模式

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Singleton {

private Singleton() {

}

private static Singleton instance = new Singleton();

public static Singleton getInstance() {
return instance;
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class Singleton {

private Singleton() {

}

private Singleton instance;

public static Singleton getInstance() {
if (instance != null) {
return instance;
}
synchronized(Singleton.class) {
if (instantce) {
if (instance != null) {
return instance;
}
instance = new Signleton();
return instance;
}
}
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Singleton {

private Singleton() {

}

public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}

private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}

}