Java单例模式

饿汉模式

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

    // 私有构造函数
    private Singleton() {}

    // 公开的构造函数
    public static Singleton getInstance() {
        return INSTANCE;
    }
}

懒汉模式

public class Singleton {
    private static volatile Singleton INSTANCE = null;

    // 私有构造函数
    private Singleton() {}

    // 线程安全的公开的构造函数
    public static Singleton getInstance() {
        if(INSTANCE == null){
            synchronized(Singleton.class){
                if(INSTANCE == null){ 
                    INSTANCE = new Singleton();
                }
            } 
        }
        return INSTANCE;
    }
}

枚举实现

public enum Singleton {    
    INSTANCE;    
    public void doSomething() {    
    }    
}    

// Call the method from Singleton:    
Singleton.INSTANCE.doSomething();