什么是单例模式
- 一个类有且仅有一个实例,并且自行实例化向整个系统提供
为什么使用单例模式
- 在有些场景下有些对象只能有一个,就比如现实中大BOSS只能有一个,否则职员不知道该听哪个老板的指令,在spring中他的IOC容器就是一个单例的。这样才能保证获取到一个唯一的实例对象。
怎么实现单例模式
双重检查
1
2
3
4
5
6
7
8
9
10
11
12
13
14public class Singleton {
private static Singleton instance = null;
private Singleton() {}
public static Singleton getInstance(){
if (null == instance){
synchronized (Singleton.class){
if (null == instance){
instance = new Singleton();
}
}
}
return instance;
}
}静态代码块
1
2
3
4
5
6
7
8
9
10
11
12
13
14public class Singleton {
static {
instance = new Singleton();
}
private static Singleton instance;
private Singleton() {
}
public static Singleton getInstance() {
return instance;
}
}静态内部类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15public class Singleton {
static {
instance = new Singleton();
}
private static Singleton instance;
private Singleton() {
}
public static Singleton getInstance() {
return instance;
}
}