1. 程式人生 > >Java 單例模式(餓漢+懶漢)

Java 單例模式(餓漢+懶漢)

java單例就是一個類始終只例項化一次

餓漢模式:在程式啟動,類載入的時候就初始化:

public class Singleton{
    private static Singleton instance = new Singleton();
    private Singleton(){}
    public static Singleton newInstance(){
        return instance;
    }
}
懶漢模式:到需要用的時候才例項化
public class Singleton {
    private static Singleton instance = null;
    private Singleton(){}
    public static synchronized Singleton getInstance(){
        if(instance == null){
            instance = new Singleton();
        }
        return instance;
    }

}