Fork me on GitHub

设计模式-单例模式

几种经典单例模式实现,参考:https://github.com/iluwatar/java-design-patterns

基础实现

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

private static final Singleton INSTANCE = new Singleton();

private Singleton() {

}

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

利用内部类实现

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

private Singleton() {

}

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

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

线程安全的懒加载实现

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

private static Singleton INSTANCE;

private Singleton() {
// 避免通过反射方式再次初始化
if (INSTANCE == null) {
INSTANCE = this;
} else {
throw new IllegalStateException("Singleton already initialized!");
}
}

public static synchronized Singleton getInstance() {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
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 final class Singleton {

private static volatile Singleton INSTANCE;

private Singleton() {
// 避免通过反射方式再次初始化
if (INSTANCE != null) {
throw new IllegalStateException("Singleton already initialized!");
}
}

public static Singleton getInstance() {
if (INSTANCE == null) {
synchronized (Singleton.class) {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
}
}
return INSTANCE;
}
}
-------------本文结束感谢您的阅读-------------