20、设计模式之单例模式-饿汉式

import java.io.Serializable;

/**
 * 饿汉式-单例模式
 * 实现Serializable接口,使其支持序列化与反序列化
 */
public class HungrySingleton implements Serializable {

    private final static HungrySingleton instance;

    static {
        instance = new HungrySingleton();
    }

    private HungrySingleton(){
        // 阻止反射攻击
        if(instance!=null){
            throw new RuntimeException("单例模式构造器禁止被反射调用");
        }
    }

    public static HungrySingleton getInstance(){
        return instance;
    }

    /**
     * 该方法解决反序列化后新对象与原对象内存地址不一致的问题
     * @return
     */
    private Object readResolve(){
        return instance;
    }
}

猜你喜欢

转载自blog.csdn.net/crystalcs2010/article/details/83275165