单例模式必须私有化构造器!
必须提供一个对外的公共的静态方法访问实例
饿汉式
// 饿汉式
// 优点:没有线程安全问题
// 缺点:提前实例化,暂用内存空间
public class HungerSingleton {
private HungerSingleton(){};
private static final HungerSingleton instance= new HungerSingleton();
public static HungerSingleton getInstance(){
return instance;
}
}
懒汉式
// 懒汉式
// 优点:用到再加载,不占用内存
public class LazySingleton {// 缺点:有线程安全问题
private LazySingleton(){};
private static LazySingleton instance= null;
public static LazySingleton getInstance(){
if(null==instance){
instance= new LazySingleton();
}
return instance;
}
}
public class LazySingleton {// 缺点:多线程访问有安全问题
private LazySingleton(){};
private static LazySingleton instance= null;
public static LazySingleton getInstance(){
if(null==instance){
// 多线程同时进入会重复创建
synchronized (LazySingleton.class){
instance= new LazySingleton();
}
}
return instance;
}
}
public class LazySingleton {// 使用双重验证保证只实例化一次
private LazySingleton(){};
private static LazySingleton instance= null;
public static LazySingleton getInstance(){
if(null==instance){
synchronized (LazySingleton.class){
if(null==instance) {
instance= new LazySingleton();
}
}
}
return instance;
}
}
静态内部类
// 静态内部类单例
public class StaticInnerSingleton {
private StaticInnerSingleton(){};
public static final StaticInnerSingleton getInstance(){
return SingletonHandle.instance;
}
private static class SingletonHandle{
private static final StaticInnerSingleton instance = new StaticInnerSingleton();
}
}
防止反序列化
// 防止反序列化获取对象
public class ReflectSingleton implements Serializable {
private ReflectSingleton(){};
private static final ReflectSingleton instance = new ReflectSingleton();
public static ReflectSingleton getInstance(){
return instance;
}
// 防止反序列化获取
// I/O流中读取时readResolve()会被调用
// 替换在反序列化过程中创建的对象
private Object readResolve() throws ObjectStreamException {
return instance;
}
}