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

                ThinkChat2.0新版上線,更智能更精彩,支持會話、畫圖、視頻、閱讀、搜索等,送10W Token,即刻開啟你的AI之旅 廣告
                ## Chapter 2. Creating and Destroying Objects(創建和銷毀對象) ### Item 5: Prefer dependency injection to hardwiring resources(依賴注入優于硬連接資源) Many classes depend on one or more underlying resources. For example, a spell checker depends on a dictionary. It is not uncommon to see such classes implemented as static utility classes (Item 4): 許多類依賴于一個或多個底層資源。例如,拼寫檢查程序依賴于字典。常見做法是,將這種類實現為靜態實用工具類([Item-4](/Chapter-2/Chapter-2-Item-4-Enforce-noninstantiability-with-a-private-constructor.md)): ``` // Inappropriate use of static utility - inflexible & untestable! public class SpellChecker { private static final Lexicon dictionary = ...; private SpellChecker() {} // Noninstantiable public static boolean isValid(String word) { ... } public static List<String> suggestions(String typo) { ... } } ``` Similarly, it’s not uncommon to see them implemented as singletons (Item 3): 類似地,我們也經常看到它們的單例實現([Item-3](/Chapter-2/Chapter-2-Item-3-Enforce-the-singleton-property-with-a-private-constructor-or-an-enum-type.md)): ``` // Inappropriate use of singleton - inflexible & untestable! public class SpellChecker { private final Lexicon dictionary = ...; private SpellChecker(...) {} public static INSTANCE = new SpellChecker(...); public boolean isValid(String word) { ... } public List<String> suggestions(String typo) { ... } } ``` Neither of these approaches is satisfactory, because they assume that there is only one dictionary worth using. In practice, each language has its own dictionary, and special dictionaries are used for special vocabularies. Also, it may be desirable to use a special dictionary for testing. It is wishful thinking to assume that a single dictionary will suffice for all time. 這兩種方法都不令人滿意,因為它們假設只使用一個字典。在實際應用中,每種語言都有自己的字典,特殊的字典用于特殊的詞匯表。另外,最好使用一個特殊的字典進行測試。認為一本字典就足夠了,是一廂情愿的想法。 You could try to have SpellChecker support multiple dictionaries by making the dictionary field nonfinal and adding a method to change the dictionary in an existing spell checker, but this would be awkward, error-prone,and unworkable in a concurrent setting. **Static utility classes and singletons are inappropriate for classes whose behavior is parameterized by an underlying resource.** 你可以嘗試讓 SpellChecker 支持多個字典:首先取消 dictionary 字段的 final 修飾,并在現有的拼寫檢查器中添加更改 dictionary 的方法。但是在并發環境中這種做法是笨拙的、容易出錯的和不可行的。**靜態實用工具類和單例不適用于由底層資源參數化的類。** What is required is the ability to support multiple instances of the class (in our example, SpellChecker), each of which uses the resource desired by the client (in our example, the dictionary). A simple pattern that satisfies this requirement is to **pass the resource into the constructor when creating a new instance.** This is one form of dependency injection: the dictionary is a dependency of the spell checker and is injected into the spell checker when it is created. 所需要的是支持類的多個實例的能力(在我們的示例中是 SpellChecker),每個實例都使用客戶端需要的資源(在我們的示例中是 dictionary)。滿足此要求的一個簡單模式是在**創建新實例時將資源傳遞給構造函數。** 這是依賴注入的一種形式:字典是拼寫檢查器的依賴項,在創建它時被注入到拼寫檢查器中。 ``` // Dependency injection provides flexibility and testability public class SpellChecker { private final Lexicon dictionary; public SpellChecker(Lexicon dictionary) { this.dictionary = Objects.requireNonNull(dictionary); } public boolean isValid(String word) { ... } public List<String> suggestions(String typo) { ... } } ``` The dependency injection pattern is so simple that many programmers use it for years without knowing it has a name. While our spell checker example had only a single resource (the dictionary), dependency injection works with an arbitrary number of resources and arbitrary dependency graphs. It preserves immutability (Item 17), so multiple clients can share dependent objects(assuming the clients desire the same underlying resources). Dependency injection is equally applicable to constructors, static factories (Item 1), and builders (Item 2). 依賴注入模式非常簡單,許多程序員在不知道其名稱的情況下使用了多年。雖然拼寫檢查器示例只有一個資源(字典),但是依賴注入可以處理任意數量的資源和任意依賴路徑。它保持了不可變性([Item-17](/Chapter-4/Chapter-4-Item-17-Minimize-mutability.md)),因此多個客戶端可以共享依賴對象(假設客戶端需要相同的底層資源)。依賴注入同樣適用于構造函數、靜態工廠([Item-1](/Chapter-2/Chapter-2-Item-1-Consider-static-factory-methods-instead-of-constructors.md))和構建器([Item-2](/Chapter-2/Chapter-2-Item-2-Consider-a-builder-when-faced-with-many-constructor-parameters.md))。 A useful variant of the pattern is to pass a resource factory to the constructor.A factory is an object that can be called repeatedly to create instances of a type.Such factories embody the Factory Method pattern [Gamma95]. The `Supplier<T>` interface, introduced in Java 8, is perfect for representing factories. Methods that take a `Supplier<T>` on input should typically constrain the factory’s type parameter using a bounded wildcard type (Item 31) to allow the client to pass in a factory that creates any subtype of a specified type. For example, here is a method that makes a mosaic using a client-provided factory to produce each tile: 這種模式的一個有用變體是將資源工廠傳遞給構造函數。工廠是一個對象,可以反復調用它來創建類型的實例。這樣的工廠體現了工廠方法模式 [Gamma95]。Java 8 中引入的 `Supplier<T>` 非常適合表示工廠。在輸入中接受 `Supplier<T>` 的方法通常應該使用有界通配符類型([Item-31](/Chapter-5/Chapter-5-Item-31-Use-bounded-wildcards-to-increase-API-flexibility.md))來約束工廠的類型參數,以允許客戶端傳入創建指定類型的任何子類型的工廠。例如,這里有一個生產瓷磚方法,每塊瓷磚都使用客戶提供的工廠來制作馬賽克: ``` Mosaic create(Supplier<? extends Tile> tileFactory) { ... } ``` Although dependency injection greatly improves flexibility and testability, it can clutter up(使雜亂) large projects, which typically contain thousands of dependencies.This clutter can be all but eliminated by using a dependency injection framework, such as Dagger [Dagger], Guice [Guice], or Spring [Spring]. The use of these frameworks is beyond the scope of this book, but note that APIs designed for manual dependency injection are trivially adapted for(適用于) use by these frameworks. 盡管依賴注入極大地提高了靈活性和可測試性,但它可能會使大型項目變得混亂,這些項目通常包含數千個依賴項。通過使用依賴注入框架(如 Dagger、Guice 或 Spring),幾乎可以消除這種混亂。這些框架的使用超出了本書的范圍,但是請注意,為手動依賴注入而設計的 API 很容易被這些框架所使用。 In summary, do not use a singleton or static utility class to implement a class that depends on one or more underlying resources whose behavior affects that of the class, and do not have the class create these resources directly. Instead, pass the resources, or factories to create them, into the constructor (or static factory or builder). This practice, known as dependency injection, will greatly enhance the flexibility, reusability, and testability of a class. 總之,不要使用單例或靜態實用工具類來實現依賴于一個或多個底層資源的類,這些資源的行為會影響類的行為,也不要讓類直接創建這些資源。相反,將創建它們的資源或工廠傳遞給構造函數(或靜態工廠或構建器)。這種操作稱為依賴注入,它將大大增強類的靈活性、可復用性和可測試性。 --- **[Back to contents of the chapter(返回章節目錄)](/Chapter-2/Chapter-2-Introduction.md)** - **Previous Item(上一條目):[Item 4: Enforce noninstantiability with a private constructor(用私有構造函數實施不可實例化)](/Chapter-2/Chapter-2-Item-4-Enforce-noninstantiability-with-a-private-constructor.md)** - **Next Item(下一條目):[Item 6: Avoid creating unnecessary objects(避免創建不必要的對象)](/Chapter-2/Chapter-2-Item-6-Avoid-creating-unnecessary-objects.md)**
                  <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>

                              哎呀哎呀视频在线观看