博客
关于我
如何破坏单例?我说了好几种方式,面试官:没想到你真会
阅读量:78 次
发布时间:2019-02-25

本文共 2362 字,大约阅读时间需要 7 分钟。

?????Singleton Pattern????????????????????????????????????????????????????????????????????????????????????????????????????????????????

????????

  • ????

    ?????????????????????????????????????????????????????????????????????????????????????????????????????

    import java.lang.reflect.Constructor;public class SingletonTest {    public static void main(String[] args) {        Singleton singleton = Singleton.getSingleton();        try {            Class
    singletonClass = Singleton.class; Constructor
    constructor = singletonClass.getDeclaredConstructor(null); constructor.setAccessible(true); Singleton singletonByReflect = constructor.newInstance(); System.out.println("singleton : " + singleton); System.out.println("singletonByReflect : " + singletonByReflect); System.out.println("singleton == singletonByReflect : " + (singleton == singletonByReflect)); } catch (Exception e) { e.printStackTrace(); } }}

    ???????????????????????????????????????

  • ?????

    ????????????????????????????????????????????????????????????

    public class SingletonTest {    public static void main(String[] args) {        Singleton singleton = Singleton.getSingleton();        try {            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("tempFile"));            oos.writeObject(singleton);            ObjectInputStream ois = new ObjectInputStream(new FileInputStream("tempFile"));            Singleton singletonBySerialize = (Singleton) ois.readObject();            System.out.println("singleton : " + singleton);            System.out.println("singletonBySerialize : " + singletonBySerialize);            System.out.println("singleton == singletonBySerialize : " + (singleton == singletonBySerialize));        } catch (Exception e) {            e.printStackTrace();        }    }}

    ?????????????????????????????????????

  • ????????

  • ??????????

    ??????????????????????????????????????????

    private Singleton() {    if (singleton != null) {        throw new RuntimeException("Singleton constructor is called...");    }}

    ???????????????????????????????

  • ?? readResolve ??

    ??????? readResolve ????????????????????????

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

    ????????????? readResolve ???????????????????????????

  • ????????????????????????????????????????????????

    转载地址:http://cns.baihongyu.com/

    你可能感兴趣的文章
    Python 中读取 CSV 文件-ChatGPT4o作答
    查看>>
    Python 之 filecmp
    查看>>
    python请求html_使用Python请求获取HTML?
    查看>>
    Python 之匿名函数和偏函数
    查看>>
    python 之栈的实现
    查看>>
    python语音播放
    查看>>
    python语言:装饰器原理
    查看>>
    Python 交互式数据可视化详解
    查看>>
    python语言有哪些优点和缺点_Python有哪些优缺点,你了解吗?
    查看>>
    Python 从入门到精通:30天速成教程到底有多狠?你能坚持下来吗?
    查看>>
    Python 从数据库中存储和检索密码的最安全方法
    查看>>
    Python语言及其应用 - 知识点遍历
    查看>>
    Python 优化提速的 8 个小技巧
    查看>>
    Python 余弦相似度与皮尔逊相关系数 计算
    查看>>