终极单例模式,饿汉式,懒汉式,枚举式

/***
 * 饿汉式单例,在类初始化时就自行实例化,这样可以避免线程安全问题,但是浪费内存空间,不推荐
 */
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;
    }
}

你可能感兴趣的:(java)