<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>

                ??一站式輕松地調用各大LLM模型接口,支持GPT4、智譜、豆包、星火、月之暗面及文生圖、文生視頻 廣告
                # 如何在 Java 中創建不可變的類 > 原文: [https://howtodoinjava.com/java/basics/how-to-make-a-java-class-immutable/](https://howtodoinjava.com/java/basics/how-to-make-a-java-class-immutable/) [不可變類](https://en.wikipedia.org/wiki/Immutable_object)是其狀態一旦創建便無法更改的類。 有某些準則可以**創建 Java** 中不可變的類。 在這篇文章中,我們將重新審視這些準則。 ```java Table of Contents 1\. Rules to create immutable classes 2\. Java immutable class example 3\. Benefits of making a class immutable 5\. Summary ``` ## 1\. 創建不可變類的規則 Java 文檔本身具有一些準則,[此鏈接中](https://docs.oracle.com/javase/tutorial/essential/concurrency/imstrat.html)的這些準則可以確定編寫不可變類。 通過使用`Date`字段創建具有可變對象的不可變類,我們將理解這些準則的實際含義。 1. #### 不要提供“設置器”方法 - 修改字段或字段引用的對象的方法。 該原則表明,對于您的類中的所有可變屬性,請勿提供設置器方法。 設置器方法用于更改對象的狀態,這是我們在此要避免的。 2. #### 將所有字段定為最終和私有的 這是增加*不變性*的另一種方法。 聲明為`private`的字段將無法在類之外訪問,并且將它們設置為最終字段將確保即使您無意中也無法更改它們。 3. #### 不允許子類覆蓋方法 最簡單的方法是將該類聲明為`final`。 Java 中的`final`類無法擴展。 4. #### 具有可變實例變量時要特別注意 始終記住,實例變量將是**可變的**或**不可變的**。 標識它們并返回具有所有可變對象復制內容的新對象。 不可變的變量可以安全地返回而無需額外的努力。 一種更復雜的方法是使構造器`private`,并在**工廠方法**中構造實例。 ## 2\. Java 不可變類示例 讓我們將以上所有規則應用于不可變類,并為 Java 中的**不可變類實現具體的類實現**。 ```java import java.util.Date; /** * Always remember that your instance variables will be either mutable or immutable. * Identify them and return new objects with copied content for all mutable objects. * Immutable variables can be returned safely without extra effort. * */ public final class ImmutableClass { /** * Integer class is immutable as it does not provide any setter to change its content * */ private final Integer immutableField1; /** * String class is immutable as it also does not provide setter to change its content * */ private final String immutableField2; /** * Date class is mutable as it provide setters to change various date/time parts * */ private final Date mutableField; //Default private constructor will ensure no unplanned construction of class private ImmutableClass(Integer fld1, String fld2, Date date) { this.immutableField1 = fld1; this.immutableField2 = fld2; this.mutableField = new Date(date.getTime()); } //Factory method to store object creation logic in single place public static ImmutableClass createNewInstance(Integer fld1, String fld2, Date date) { return new ImmutableClass(fld1, fld2, date); } //Provide no setter methods /** * Integer class is immutable so we can return the instance variable as it is * */ public Integer getImmutableField1() { return immutableField1; } /** * String class is also immutable so we can return the instance variable as it is * */ public String getImmutableField2() { return immutableField2; } /** * Date class is mutable so we need a little care here. * We should not return the reference of original instance variable. * Instead a new Date object, with content copied to it, should be returned. * */ public Date getMutableField() { return new Date(mutableField.getTime()); } @Override public String toString() { return immutableField1 +" - "+ immutableField2 +" - "+ mutableField; } } ``` 現在該測試我們的類了: ```java class TestMain { public static void main(String[] args) { ImmutableClass im = ImmutableClass.createNewInstance(100,"test", new Date()); System.out.println(im); tryModification(im.getImmutableField1(),im.getImmutableField2(),im.getMutableField()); System.out.println(im); } private static void tryModification(Integer immutableField1, String immutableField2, Date mutableField) { immutableField1 = 10000; immutableField2 = "test changed"; mutableField.setDate(10); } } ``` 程序輸出: ```java 100 - test - Tue Oct 30 21:34:08 IST 2012 100 - test - Tue Oct 30 21:34:08 IST 2012 ``` 可以看出,即使使用其引用更改實例變量也不會更改其值,因此該類是不可變的。 #### JDK 中的不可變類 除了您編寫的類,JDK 本身還有很多不可變的類。 給出了這樣的 Java 不可變類的列表。 1. `String` 2. 包裝器類,例如`Integer`,`Long`,`Double`等。 3. 不可變的集合類,例如`Collections.singletonMap()`等。 4. `java.lang.StackTraceElement` 5. Java 枚舉(理想情況下應該如此) 6. `java.util.Locale` 7. `java.util.UUID` ## 3\. 使類不可變的好處 首先讓我們確定不可變類的**優勢。 在 Java 中,不可變類:** 1. 易于構建,測試和使用 2. 自動是線程安全的,并且沒有同步問題 3. 不需要復制構造器 4. 不需要克隆的實現 5. 允許 [`hashCode()`](//howtodoinjava.com/java/related-concepts/working-with-hashcode-and-equals-methods-in-java/ "Working with hashCode and equals methods in java") 使用延遲初始化,并緩存其返回值 6. 用作字段時不需要防御性地復制 7. 作為良好的[映射的鍵和集合元素](//howtodoinjava.com/java/collections/how-hashmap-works-in-java/ "How hashmap works in java")(在集合中這些對象不得更改狀態) 8. 在構造時就建立了其類不變式,因此無需再次檢查 9. 始終具有“**失敗原子性**”(約書亞·布洛赫(Joshua Bloch)使用的術語):如果不可變對象引發異常,則它永遠不會處于不希望或不確定的狀態 ## 4\. 總結 在本教程中,我們學習了**使用可變對象**和不可變字段創建不可變的 Java 類。 我們還看到了不可變類在應用程序中帶來的好處。 作為最佳設計實踐,始終旨在使您的應用程序 Java 類不可變。 這樣,您始終可以減少程序中與[并發](https://howtodoinjava.com/java-concurrency-tutorial/)相關的缺陷的擔心。 如何編寫一個不可變的類? 這也可能是[面試問題](https://howtodoinjava.com/java-interview-questions/)。 學習愉快! 閱讀更多: [為什么字符串類在 Java 中是不可變的?](https://howtodoinjava.com/java/string/java-interview-question-why-strings-are-immutable/)
                  <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>

                              哎呀哎呀视频在线观看