zoukankan      html  css  js  c++  java
  • 使用单元素枚举实现单例

    如果不涉及到线程安全及延迟加载,单例最简单的写法:

    public class SingletonTest {
        public static SingletonTest instance = new SingletonTest();
        private SingletonTest(){
            
        }
    }

    考虑到线程安全跟延迟加载,修改如下:

    public class SingletonTest {
        public static SingletonTest getInstance(){
            return SingletonTestHolder.instance;
        }
        private SingletonTest(){
            
        }
        static class SingletonTestHolder{
            private static final SingletonTest instance = new SingletonTest();
        }
    }

    这段代码不能解决反射攻击,及序列化的时候,readobject会返回新的对象,需要添加readResolve()方法,并且需要声明所有实例域都是transient(参考effective java第二章)

    可以通过单元素枚举来解决以上问题:

    public enum SingletonTest {
        instance;
        private int otherField;
    }

    缺点就是使用enum,无法使用类原本的功能比如继承。所以在合适的场合选择合适的单例写法吧

  • 相关阅读:
    nvalid bound statement (not found)
    小程序
    maven启动项目时报错
    创建Maven项目出错
    小程序的tab标签实现效果
    C# 异步
    C#中计算时间差
    linq筛选唯一
    GMap.net控件学习记录
    nodepad++ 正则 替换
  • 原文地址:https://www.cnblogs.com/hithlb/p/4199025.html
Copyright © 2011-2022 走看看