单例模式

2019-11-12 16:05:54来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

单例模式

单例模式实现;

灭霸所有单例模式,克隆、序列化、反射机制破坏7种单例模式;

枚举实现单例;

 破坏单例模式测试代码

import java.io.Serializable;

public class Singleton implements Cloneable, Serializable {
    private static volatile Singleton singleton;

    private Singleton() {
        if (null != singleton) {
            throw new RuntimeException();
        }
    }

    public static Singleton getInstance() {
        if (singleton == null) {
            synchronized (Singleton.class) {
                if (singleton == null) {
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }

    /**
     * 防止克隆攻击
     *
     * @return
     * @throws CloneNotSupportedException
     */
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    private Object readResolve() {
        return getInstance();
    }
}

 

public class Test1 {
    public static void main(String[] args) throws CloneNotSupportedException {
        Singleton singleton = Singleton.getInstance();
        Singleton singleton1 = (Singleton) singleton.clone();
        Singleton singleton2 = Singleton.getInstance();
        System.out.println(singleton.hashCode());
        System.out.println(singleton1.hashCode());
        System.out.println(singleton2.hashCode());
    }
}

 

public class Test2 {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Singleton singleton = Singleton.getInstance();
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("d:\\xttblog.obj"));
        oos.writeObject(singleton);
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("d:\\xttblog.obj")));
        Singleton singleton1 = (Singleton) ois.readObject();
        System.out.println(singleton.hashCode());
        System.out.println(singleton1.hashCode());
        System.out.println(singleton == singleton1);
    }
}

 

public class Test3 {
    public static void main(String[] args) throws ReflectiveOperationException {
        Singleton singleton1 = Singleton.getInstance();
        Class cls = Singleton.class;
        Constructor<Singleton> constructor = cls.getDeclaredConstructor();
        constructor.setAccessible(true);
        Singleton singleton = constructor.newInstance();
        System.out.println(singleton.hashCode());
        System.out.println(singleton1.hashCode());
        System.out.println(singleton == singleton1);
    }
}

 


原文链接:https://www.cnblogs.com/liran123/p/11843180.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:dubbo解决本地开发直连

下一篇:十二、Spring之IOC容器初始化