究極の単例モード、餓漢式、怠け者式、列挙式

3205 ワード

/***
 *      ,            ,            ,        ,   
 */
public class HungrySingleton {
    private HungrySingleton() {
    }

    private static final HungrySingleton singleton = new HungrySingleton();

    public static HungrySingleton getSingleton() {
        return singleton;
    }

    //         
    public Object realResoler() {
        return singleton;
    }

}
/***
 *     (     ),  
 */
public class LazySingleton2 {

    private static boolean initialized = false;

    //      (   ),         
    private static class LazyHolder {
        private static final LazySingleton2 LAZY = new LazySingleton2();
    }

    private LazySingleton2() {

        //         
        synchronized (LazySingleton2.class) {
            if (!initialized) {
                initialized = true;
            } else {
                throw new RuntimeException("     ...");
            }
        }
    }

    public static LazySingleton2 getInstance() {
        return LazyHolder.LAZY;
    }

}
/***
 *        ,   ,   ,      ,      ,     jdk,         
 */
public enum RegisterSingleton {

    INSTANCE;

    public RegisterSingleton getInstance() {
        return INSTANCE;
    }
}