单例模式之枚举

众所周知,在java中有多种方式创建单例:饿汉式,懒汉式,双重检测懒汉式,静态内部类等,这些单列模式各有缺点:

  1. 有的类加载时就初始化,浪费内存
  2. 有的不保证多线程安全
  3. 有的因为加了synchronized同步锁导致并发效率较低
  4. 以上的单例模式都能通过反射,反序列化,克隆等方式被破坏
public class SingletonTestDoubleCheck implements Cloneable, Serializable {

    public SingletonTestDoubleCheck() {
    }

    private static volatile SingletonTestDoubleCheck singletonTestDoubleCheck;

    //双重检测 懒汉式单例
    public static SingletonTestDoubleCheck getSingleton() {
        if (singletonTestDoubleCheck == null) {
            synchronized (SingletonTestDoubleCheck.class) {
                if (singletonTestDoubleCheck == null) {
                    singletonTestDoubleCheck = new SingletonTestDoubleCheck();
                }
            }
        }
        return singletonTestDoubleCheck;
    }

    @Override
    protected SingletonTestDoubleCheck clone() throws CloneNotSupportedException {
        return (SingletonTestDoubleCheck)super.clone();
    }

    //破坏单例的方式
    public static void main(String[] args) {
        SingletonTestDoubleCheck singletonTestDoubleCheck = SingletonTestDoubleCheck.getSingleton();
        try {
            //1.通过反射的方式
            Constructor<SingletonTestDoubleCheck> declaredConstructor = SingletonTestDoubleCheck.class.getDeclaredConstructor();
            declaredConstructor.setAccessible(true);
            SingletonTestDoubleCheck singleReflect = declaredConstructor.newInstance();
            System.out.println("============反射===========");
            System.out.println(singletonTestDoubleCheck == singleReflect);

            //2.通过序列的方式(记得实现序列化Serializable接口)
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("SingletonSerializable"));
            oos.writeObject(singletonTestDoubleCheck);
            oos.flush();
            oos.close();
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream("SingletonSerializable"));
            SingletonTestDoubleCheck singletonSerializable = (SingletonTestDoubleCheck)ois.readObject();
            ois.close();
            System.out.println("============序列化===========");
            System.out.println(singletonTestDoubleCheck == singletonSerializable);

            //3.克隆(记得重写clone方法,重写clone方法需要实现Cloneable接口)
            SingletonTestDoubleCheck singleClone = singletonTestDoubleCheck.clone();
            System.out.println("============克隆===========");
            System.out.println(singletonTestDoubleCheck == singleClone);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

枚举能解决上面所述问题,同时也是我认为最简便的单例模式

public enum SingletonTestEnum {
    INSTANCE;

    SingletonTestEnum() {
        System.out.println("NoArgsConstructor");
    }

    public static void main(String[] args) {
        SingletonTestEnum instance = SingletonTestEnum.INSTANCE;
        try {
            //1.通过反射的方式
            //枚举有无参构造器,但是默认是用private修饰,而且也只能是private
            //所以无法通过反射获取它的无参构造器
            Constructor<SingletonTestEnum> declaredConstructor = SingletonTestEnum.class.getDeclaredConstructor();
            declaredConstructor.setAccessible(true);
            SingletonTestEnum singletonTestEnum = declaredConstructor.newInstance();
            System.out.println("============反射===========");
            System.out.println(instance == singletonTestEnum);
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            //2.通过序列化的方式
            //枚举默认就实现了Serializable接口: public abstract class Enum>implements Comparable, Serializable{...}
            //序列化时,对应ObjectOutputStream的void writeObject(Object obj)方法,该方法的具体实现中,会根据obj的具体类型实施不同的序列化方式。当为Enum类型时,只会把Enum中定义的属性name输出到结果中。
            //反序列化时,ObjectInputStream的Object readObject()方法发现需要反序列化的是Enum类型,就调用Enum的T valueOf(Class enumType,String name)方法,根据name拿到对应的枚举实例。
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("SingletonSerializable"));
            oos.writeObject(instance);
            oos.flush();
            oos.close();
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream("SingletonSerializable"));
            SingletonTestEnum singletonSerializable = (SingletonTestEnum)ois.readObject();
            ois.close();
            System.out.println("============序列化===========");
            System.out.println(instance == singletonSerializable);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //3.克隆
        //protected final Object clone() throws CloneNotSupportedException {
        //      throw new CloneNotSupportedException();
        //}
        //枚举类的克隆方法是final的,会直接抛出异常,所以也就不存在克隆破坏单例的情况
    }

}
```.
枚举类中,INSTANCE其实是它的枚举项,不能使用new的方式来创建枚举类的对象,因为枚举中的实例本质就是它的枚举项,只能用枚举类名.枚举项的方式获取该实例.创建枚举项等用于调用本类的无参构造器,在运行上诉方法时,你会看到输出"NoArgsConstructor"

你可能感兴趣的:(Java,单例模式,java)