0%

设计模式_单例

懒汉式

​ 需要使用时再加载

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

private static SingleInstanceLazy instance;

private SingleInstanceLazy(){}

public static synchronized SingleInstanceLazy getInstance(){
if (instance == null) {
instance = new SingleInstanceLazy();
}
return instance;
}
}

饿汉式

​ 类初始化时就加载,调用时直接使用

1
2
3
4
5
6
7
8
9
10
public class SingleInstanceStarvation {

private static final SingleInstanceStarvation instance = new SingleInstanceStarvation();

private SingleInstanceStarvation(){}

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

双检查DCL式

​ 防止多线程并发访问问题,方法加同步锁

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class SingleInstanceDCL {

private static volatile SingleInstanceDCL instance;

private SingleInstanceDCL() {}

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

静态内部类式

​ 除方法加同步锁外,用静态内部类的方式同样可以防止多线程并发问题

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

private SingleInstanceStatic(){}

public static SingleInstanceStatic getInstance(){
return SingleInstanceHolder.instance;
}

private static class SingleInstanceHolder{
private static final SingleInstanceStatic instance = new SingleInstanceStatic();
}
}