单例实现方式:

  • i_f48.gifUse enum which is recommended by Josh Bloch, the author of Effective Java.

public enum Singleton {
    INSTANCE;
    public String hello() {
        return "hello";
    }
}


  • 饿汉

public class Singleton {
    private static final Singleton INSTANCE = new Singleton();
    private Singleton() {
    }
    public static Singleton getInstance() {
        return INSTANCE;
    }
}


  • 懒汉 Double-checked Locking, since Java 5

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