单例设计模式

2018, Apr 18    

单例设计模式

单例模式:让对象独一无二

  • 优点:内存中之后一个实例,减少内存开支
  • 缺点:单例模式一般没有接口,扩展很困难
  1. 饿汉单例

    public class Singleton {
        private static final Singleton singleton = new Singleton();
           
        public static Singleton getInstance() {
            return singleton;
        }
    }
    
  2. 懒汉单例

    public class Singleton {
        private static Singleton singleton;
           
        public static Singleton getInstance() {
            if (singleton == null) {
                singleton = new Singleton();
            }
            return singleton;
        }
    }
    
  3. 双重检查单例

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