只生成唯一的对象。
有以下几种实现方式,推荐第一种。
public class Singleton {
//利用静态内部类的静态变量来初始化唯一对象,且在调用的时候才加载SingleHolder类,实现懒加载的效果,也保证了线程安全
private static class SingleHolder{
private static Singleton instance = new Singleton();
}
public static Singleton getInstance(){
return SingleHolder.instance;
}
public static void main(String[] args) {
Singleton instance01 = Singleton.getInstance();
Singleton instance02 = Singleton.getInstance();
System.out.println(instance01 == instance02);
SingleFive singleFive01 = SingleFive.INSTANCE;
SingleFive singleFive02 = SingleFive.INSTANCE;
System.out.println(singleFive01 == singleFive02);
}
}
//饿汉式单例
class SingleOne{
private static SingleOne instance = new SingleOne();
private SingleOne(){}
public static SingleOne getInstance(){
return instance;
}
}
//懒加载,也叫懒汉式单例,致命的是在多线程不能正常工作
class SingleTwo{
private static SingleTwo instance = null;
private SingleTwo(){}
public static SingleTwo getInstance(){
if(instance == null){
instance = new SingleTwo();
}
return instance;
}
}
//懒加载,遗憾的是,效率很低,99%情况下不需要同步
class SingleThree{
private static SingleThree instance;
private SingleThree(){}
public static synchronized SingleThree getInstance(){
if(instance == null){
instance = new SingleThree();
}
return instance;
}
}
//懒加载,线程安全,双重校验锁法
class SingleFour{
private volatile static SingleFour instance;
private SingleFour(){}
public static SingleFour getInstance(){
if(instance == null){
synchronized(SingleFour.class){
if(instance == null){
instance = new SingleFour();
}
}
}
return instance;
}
}
//枚举,Effective Java作者Josh Bloch 提倡的方式,它不仅能避免多线程同步问题,而且还能防止反序列化重新创建新的对象
enum SingleFive {
INSTANCE;
}