Effective Java

强化Singleton属性

2017-03-16  本文已影响21人  大海孤了岛

法则:用私有构造器或枚举类型强化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;
    }
}

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

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());
    }

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

上一篇 下一篇

猜你喜欢

热点阅读