定义
确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。
使用场景
确保某个类有且只有一个对象的场景,避免产生多个对象消耗过多的资源,或者某种类型的对象只应该有且只有一个。
常见的实现方式
1、懒汉模式
public class People {
private static People instance;
private People(){}
public static synchronized People getInstance(){
if (instance == null){
instance = new People();
}
return instance;
}
}
2、饿汉模式
public class People {
private static People instance = new People();
private People(){}
public static People getInstance(){
return instance;
}
}
3、Double Check Lock(DCL) (建议使用)
public class People {
private static People instance;
private People(){}
public static People getInstance(){
if (instance == null){
synchronized (People.class){
if (instance == null){
instance = new People();
}
}
}
return instance;
}
}
4、静态内部类 (建议使用)
public class People {
private People(){}
public static People getInstance(){
return PeopleHolder.people;
}
private static class PeopleHolder{
private static final People people = new People();
}
}