注意:实现一个单例有两点注意事项,
①将构造器私有,不允许外界通过构造器创建对象;
②通过公开的静态方法向外界返回类的唯一实例。
饿汉式单例
public class Singleton implements serializable{
private Singleton(){}
private static Singleton INSTANCE = new Singleton();
public static Singleton getInstance(){
if(INSTANCE !=null){ //防止反射破坏单例
throw new RuntimeException(“单例对象不能被重复创建”);
}
return INSTANCE ;
}
public Object readResolve(){
return INSTANCE ;//防止反序列化破坏单例
}
}
Unsafe破坏单例
懒汉式单例
双重检查锁定
public class Singleton implements serializable{
private static voilter Singleton INSTANCE = null;
private Singleton() {}
public static Singleton getInstance(){
if (INSTANCE == null){
synchronized (Singleton .class){
if (INSTANCE == null)
INSTANCE = new Singleton();
return INSTANCE ;
}
}
}
}
静态内部类-懒汉式
public class Singleton implements serializable{
private static class LazyHolder {
static Singleton INSTANCE = new Singleton();
}
private Singleton (){}
public static final Singleton getInstance() {
return LazyHolder.INSTANCE;
}
}
既实现了线程安全,又避免了同步带来的性能影响
枚举-饿汉式
public enum Singleton {
INSTANCE;
public static Singleton getInstance() {
return INSTANCE;
}
}
枚举既能避免多线程同步问题,又能防止反序列化重新创建新的对象。