首页 > 代码库 > 设计模式:单例

设计模式:单例

  •  传统的实现方法:两私一公,涉及线程安全问题(即使有多重检查锁也可以通过反射破坏单例)
public class Singleton {
    private volatile static Singleton instance = null;
    
    private Singleton () {
    }
    
    public static Singleton getSingleton() {
        if(instance == null) {
            synchronized(Singleton.class) {
                if(instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}
  • JDK1.5以前
public class Singleton {
    private static class SingletonInstance {
        private static final Singleton instance = new Singleton();
    }
    
    private Singleton() {
    }
    
    public static Singleton getSingleton() {
        return SingletonInstance.instance;
    }
}
  •  目前最为安全的实现单例的方法是通过内部静态enum的方法来实现,因为JVM会保证enum不能被反射并且构造器方法只执行一次。
public class Singleton {
    private Singleton() {}

    public static Singleton getInstance() {
        return SingletonEnum.INSTANCE.getInstance();
    }
    
    
    private static enum SingletonEnum {
        INSTANCE;
        private Singleton singleton = null;
        private SingletonEnum() {
            singleton = new Singleton();
        }
        
        public Singleton getInstance() {
            return this.singleton;
        }
    }
    
    public static void main(String[] args) {
        Singleton singleton1 = Singleton.getInstance();
        Singleton singleton2 = Singleton.getInstance();
        
        System.out.println("singleton1==singleton2? " + (singleton1==singleton2));
    }
}

 

设计模式:单例