如何才能搞懂Java設(shè)計模式?從最重要的單例模式開始吧!

如何才能搞懂Java設(shè)計模式?從最重要的單例模式開始吧!

單例模式

餓漢式

// 餓漢式單例
public class Hungry {

    // 浪費空間
    private byte[] data1 = new byte[1024 * 1024];
    private byte[] data2 = new byte[1024 * 1024];
    private byte[] data3 = new byte[1024 * 1024];
    private byte[] data4 = new byte[1024 * 1024];
    加入Java開發(fā)交流君樣:484138291一起吹水聊天
    private Hungry() {

    }

    private final static Hungry HUNGRY = new Hungry();

    public static Hungry getInstance() {
        return HUNGRY;
    }

}

懶漢式

// 懶漢式單例
public class Lazy {

    private static boolean flag = false;

    private Lazy() {
        synchronized (Lazy.class) {
            if (flag == false) {
                flag = true;
            } else {
                throw new RuntimeException("不要使用反射");
            }
        }
//        if (lazy != null) {
//            throw new RuntimeException("不要使用反射");
//        }加入Java開發(fā)交流君樣:484138291一起吹水聊天
        System.out.println(Thread.currentThread().getName());
    }

    private volatile static Lazy lazy;

    // 雙重檢測鎖模式的  懶漢式單例 DCL 懶漢式
    public static Lazy getInstance() {
        if (lazy == null) {
            synchronized (Lazy.class) {
                if (lazy == null) {
                    lazy = new Lazy(); // 不是一個原子性操作
                    /*
                     *  1\. 分配內(nèi)存空間
                     *  2\. 執(zhí)行構(gòu)造方法 初始化對象
                     *  3\. 把這個對象指向這個空間
                     *  123
                     *  132 A
                     *      B  此時Lazy還沒有完成構(gòu)造
                     * */
                }
            }
        }

        return lazy;
    }

    public static void main(String[] args) throws Exception {
//        Lazy lazy1 = Lazy.getInstance();
        Constructor<Lazy> declaredConstructor = Lazy.class.getDeclaredConstructor(null);
        declaredConstructor.setAccessible(true);

        Lazy lazy2 = declaredConstructor.newInstance();
        Field flag = Lazy.class.getDeclaredField("flag");
        flag.setAccessible(true);
        flag.set("flag", false);

        Lazy lazy3 = declaredConstructor.newInstance();
//        System.out.println(lazy1);
        System.out.println(lazy2);
        System.out.println(lazy3);
    }

//    public static void main(String[] args) {
//        for (int i = 0; i < 10; i++) {
//            new Thread(() -> {
//                Lazy.getInstance();
//            }).start();
//        }
//    }

}

靜態(tài)內(nèi)部類

// 靜態(tài)內(nèi)部類
public class Holder {
    private Holder(){

    }

    public static Holder getInstance() {
        return InnerClass.HOLDER;
    }

    public static class InnerClass{
        private static final Holder HOLDER = new Holder();
    }
}

因為有反射 所以單例不安全 枚舉類

// enum 本事也是一個Class類
public enum EnumSingle {

    INSTANCE;

    public EnumSingle getInstance() {
        return INSTANCE;
    }

}

class  test{
    public static void main(String[] args) throws Exception {
        EnumSingle instance1 = EnumSingle.INSTANCE;
        Constructor<EnumSingle> declaredConstructor = EnumSingle.class.getDeclaredConstructor(String.class, int.class);
        declaredConstructor.setAccessible(true);
        EnumSingle instance2 = declaredConstructor.newInstance();
        System.out.println(instance1);
        System.out.println(instance2);
    }
}

分類: Java設(shè)計模式

最新2021整理收集的一些高頻面試題(都整理成文檔),有很多干貨,包含mysql,netty,spring,線程,spring cloud、jvm、源碼、算法等詳細(xì)講解,也有詳細(xì)的學(xué)習(xí)規(guī)劃圖,面試題整理等,需要獲取這些內(nèi)容的朋友請加Q君樣:484138291

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容