单例模式

饿汉式

1
2
3
4
5
6
7
8
9
10
11
12
13
class Demo {
private static Demo instance;

private Demo() {}

static {
instance = new Demo();
}

public static Demo getInstance() {
return instance;
}
}

注:在类加载的时候就吃资源。

懒汉式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Demo {
private static volatile Demo instance;

private Demo() {}

public static Demo getInstance() {
if (instance==null){
synchronized (Demo.class) {
if (instance==null){
instance = new Demo();
}
}
}
return instance;
}
}

注:在调用时才实例化对象。

静态内部类

1
2
3
4
5
6
7
8
9
10
11
12
13
class Demo {
private static volatile Demo instance;

private Demo() {}

private static class DemoInstance {
private static final Demo INSTANCE = new Demo();
}

public static Demo getInstance() {
return DemoInstance.INSTANCE;
}
}

枚举

1
2
3
4
5
6
enum Demo {
INSTANCE;
public void echo() {
System.out.println("echo");
}
}

单例模式
https://wangqian0306.github.io/2020/design-pattern-singleton/
作者
WangQian
发布于
2020年6月15日
许可协议