<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                # 枚舉真的是最好的單例嗎? > 原文: [https://howtodoinjava.com/java/enum/is-enum-really-best-for-singletons/](https://howtodoinjava.com/java/enum/is-enum-really-best-for-singletons/) 您必須多次聽到**枚舉始終是在 Java 中實現單例設計模式**的最佳選擇。 他們真的最好嗎? 如果可以的話,它比其他可用技術更好嗎? 讓我們找出答案。 編寫單例實現總是很棘手。 我在[**博客文章**](//howtodoinjava.com/design-patterns/singleton-design-pattern-in-java/)中已經討論了幾種方法(包括我最喜歡的方法)。 我在那里寫清楚,枚舉為線程安全提供了隱式支持,并且只保證了一個實例。 這也是**以最小的努力**獲得單例的好方法。 ## 枚舉作為單例的問題 話雖這么說,就像宇宙中的任何其他事物一樣,這種方法確實有其缺點,您在做出任何決定之前需要考慮這些缺點。 1. 默認情況下,枚舉不支持**延遲加載**。 2. 雖然這種情況非常罕見,但是如果您改變主意并現在想將**單例轉換為多例,枚舉將不允許**。 如果以上兩種情況對任何人都沒有問題,則枚舉可能是最佳選擇。 無論如何,順便說一句,編譯后,java 枚舉只能通過其他方法(例如 `values()`和`valueOf()`…等)轉換為類。 ## 基于枚舉的單例示例 一旦您決定編寫基于**枚舉的單例**,編寫它就非常容易,例如 ```java enum Singleton { INSTANCE; // instance vars, constructor private final Connection connection; Singleton() { // Initialize the connection connection = DB.getConnection(); } // Static getter public static Singleton getInstance() { return INSTANCE; } public Connection getConnection() { return connection; } } ``` 現在您可以使用`final Singleton s = Singleton.getInstance()`了。 請記住,由于這是一個枚舉,因此您也始終可以通過`Singleton.INSTANCE`進行訪問。 學習愉快!
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看