单例模式

概念

单例模式(Singleton Pattern)目的是保证虚拟机中只有一个实例。

Java实现

饿汉模式

懒汉模式

1
2
3
4
5
6
7
8
9
10
11
12
public class Singleton {
private final static Singleton singleton = new Singleton();

private Singleton() {

}

public static Singleton getInstance() {
return singleton;
}

}

懒汉模式

方法锁模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Singleton {
private static Singleton singleton;

private Singleton() {

}

public static synchronized Singleton getInstance() {

if (singleton == null) {
singleton = new Singleton();
}

return singleton;
}

}

双重锁模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Singleton {
private volatile static Singleton singleton;

private Singleton() {

}

public static Singleton getInstance() {

if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}

return singleton;
}

}
Author: suce
Link: https://haoubox.cn/2021/06/06/单例模式/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.