设计模式-单例模式

你离开我真会死。 提交于 2019-11-27 07:40:12
  1. 饿汉式单例

    // 缺点: 在类不使用时也会加载,浪费内存
    class Singleton {
        private static final Singleton INSTANCE = new Singleton();
    
        private Singleton() {}
    
        public static Singleton getInstance() {
            return INSTANCE;
        }
    }    
  2. 同步单例

    // 缺点:在类创建成功后其实不需要同步,性能低
    class Singleton {
        private static Singleton instance;
    
        private Singleton() {}
    
        public static synchronized Singleton getInstance() {
            if (instance == null) {
                instance = new Singleton();
            }
            return instance;
        }
    }
  3. 双重检查锁单例

    // 缺点:写法复杂,仍需要同步
    class Singleton {
        private static volatile Singleton instance;
    
        private Singleton() {}
    
        public static Singleton getInstance() {
            if (instance == null) {
                synchronized (Singleton.class) {
                    if (instance == null) {
                        instance = new Singleton();
                    }
                }
            }
            return instance;
        }
    }    
  4. 静态内部类单例

    // 优点: 1.延迟初始化,不占用内存;2.无需同步,通过jvm类加载保证线程安全  
    class Singleton {
    
        private Singleton() {}
    
        private static class SingletonHolder {
            private static final Singleton INSTANCE = new Singleton();
        }
    
        public static Singleton getInstance() {
            return SingletonHolder.INSTANCE;
        }
    }
  5. 枚举类单例

    // 优点: 写法简单,序列化安全,避免反射攻击
    // 没有懒加载
    public enum Singleton {
    
        INSTANCE;
    
        public static Singleton getInstance() {
            return INSTANCE;
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!