强化Singleton属性


法则:用私有构造器或枚举类型强化Singleton属性

实现Singleton的三种方法:

  • 把构造器保持为私有的,并导出公有的静态成员。
  • 把构造器保持为私有的,并导出公有的静态工厂方法。
  • 使用单元素的枚举类型来实现。
直接调用INSTANCE
public class Singleton{

    public static final Singleton INSTANCE = new Singleton();

    private Singleton(){}
}
使用静态方法getInstance获取
public class Singleton implements Serializable{

    private static final Singleton INSTANCE = new Singleton();
    private Singleton(){}
    public static Singleton getInstance(){
        return INSTANCE;
    }
}

以上两种方法可能存在如下问题:

  • 享有特权的客户端可以借助AccessibleObject.setAccessible方法,通过反射机制调用私有构造器。

  • 若Singleton类实现可序列化的,会导致每次反序列化都会产生一个新的实例。

  • 针对问题一,我们通常会在私有的构造函数中,添加一个判断,若实例已存在,则抛出一个异常。

private Singleton(){
        if (INSTANCE != null){
            throw new UnsupportedOperationException("Instance already exist");
        }
    }
  • 针对问题二,我们先看下没有做任何处理时的效果:

a. 让Singleton类实现Serializable:

public class Singleton implements Serializable{

    private static final Singleton INSTANCE = new Singleton();

    private Singleton(){
        if (INSTANCE != null){
            throw new UnsupportedOperationException("Instance already exist");
        }
    }

    public static Singleton getInstance(){
        return INSTANCE;
    }
}

b. 进行序列化和反序列化:

public class SingletonTest {
    public static void main(String[] args){
        try {
            serialize(Singleton.getInstance(),"singleton");
            deserialize("singleton");
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 实现序列化
     * @param singleton 传入的Singleton对象
     * @param filename 传入的文件名
     * @throws IOException
     */
    public static void serialize(Singleton singleton, String filename) throws IOException {
        FileOutputStream fos = new FileOutputStream(filename);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        //写入文件
        oos.writeObject(singleton);
        //打印序列化的对象
        System.out.println("Before serialize: " + singleton);
        oos.flush();
    }

    /**
     *  实现反序列化
     * @param filename 文件名
     * @return
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public static Singleton deserialize(String filename) throws IOException, ClassNotFoundException {
        FileInputStream fis = new FileInputStream(filename);
        ObjectInputStream ois = new ObjectInputStream(fis);
        //读取到反序列化对象
        Singleton singleton = (Singleton) ois.readObject();
        //打印对象
        System.out.println("After deserialize: " + singleton);
        return singleton;
    }

}

c. 实现结果如下:

Before serialize: single_mode.Singleton@14ae5a5
After deserialize: single_mode.Singleton@448139f0

我们可以看到序列化前后两个对象实例并不是一样的。

d. 解决方法:重写readResolve方法,返回Instance单例:

public class Singleton implements Serializable{

    private static final Singleton INSTANCE = new Singleton();

    private Singleton(){
        if (INSTANCE != null){
            throw new UnsupportedOperationException("Instance already exist");
        }
    }

    public static Singleton getInstance(){
        return INSTANCE;
    }

    private Object readResolve(){
        return INSTANCE;
    }
}

更多相关

使用单元素的枚举类型:
public enum Singleton {
    INSTANCE;

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

使用方法:

public static void main(String[] args){
        Singleton.INSTANCE.setName("test");
        System.out.println(Singleton.INSTANCE.getName());
    }

这种方法在功能上与公有域方法相近,但是它更简洁,无偿地提供了序列化机制,防止多次序列化,即使是在面对复杂的序列化或者反射攻击时。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容