1. 程式人生 > >終極單例模式,餓漢式,懶漢式,列舉式

終極單例模式,餓漢式,懶漢式,列舉式

/***
 * 餓漢式單例,在類初始化時就自行例項化,這樣可以避免執行緒安全問題,但是浪費記憶體空間,不推薦
 */
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;
    }
}