设计模式-单例模式

  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;
        }
    }
    
posted @ 2019-08-14 13:35  bosslv  阅读(103)  评论(0编辑  收藏  举报