【剣指offer-Java版】02単例モードを実現


シングルスレッドバージョン

    public class _Q02Singleton {

    private static _Q02Singleton instance = null;
    private _Q02Singleton(){}

    public static _Q02Singleton getInstance(){
        if(instance == null){
            instance = new _Q02Singleton();
            return instance;
        }
        return instance;
    }
    }

マルチスレッドバージョン1

    public class _Q02Singleton2 {

    //  , , , 
    private static _Q02Singleton2 instance = new _Q02Singleton2(); 
    private _Q02Singleton2(){}

    public static _Q02Singleton2 getInstance(){
        return instance;
    }
    }

マルチスレッドバージョン2:

    public class _Q02Singleton3 {

    private static _Q02Singleton3 instance = null;
    private _Q02Singleton3(){}

    public static _Q02Singleton3 getInstance(){
        if (instance == null) {  //  , 
            synchronized (_Q02Singleton3.class) {
                if (instance == null) { // must
                    instance = new _Q02Singleton3(); //  
                }
            }
        }

        return instance;
    }
    }