Many classes depend on one or more underlying(adj.潛在的糠爬,根本的) 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):
許多類依賴于一個(gè)或多個(gè)底層資源。例如鳞上,拼寫檢查程序依賴于字典琳水。常見做法是肆糕,將這種類實(shí)現(xiàn)為靜態(tài)實(shí)用工具類(Item-4):
// 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):
類似地,我們也經(jīng)吃谛ⅲ看到它們的單例實(shí)現(xiàn)(Item-3):
// 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.
這兩種方法都不令人滿意诚啃,因?yàn)樗鼈兗僭O(shè)只使用一個(gè)字典。在實(shí)際應(yīng)用中浑玛,每種語(yǔ)言都有自己的字典绍申,特殊的字典用于特殊的詞匯表。另外顾彰,最好使用一個(gè)特殊的字典進(jìn)行測(cè)試极阅。認(rèn)為一本字典就足夠了,是一廂情愿的想法涨享。
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 支持多個(gè)字典:首先取消 dictionary 字段的 final 修飾筋搏,并在現(xiàn)有的拼寫檢查器中添加更改 dictionary 的方法。但是在并發(fā)環(huán)境中這種做法是笨拙的厕隧、容易出錯(cuò)的和不可行的奔脐。靜態(tài)實(shí)用工具類和單例不適用于由底層資源參數(shù)化的類。
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.
所需要的是支持類的多個(gè)實(shí)例的能力(在我們的示例中是 SpellChecker)吁讨,每個(gè)實(shí)例都使用客戶端需要的資源(在我們的示例中是 dictionary)髓迎。滿足此要求的一個(gè)簡(jiǎn)單模式是在創(chuàng)建新實(shí)例時(shí)將資源傳遞給構(gòu)造函數(shù)。 這是依賴注入的一種形式:字典是拼寫檢查器的依賴項(xiàng)建丧,在創(chuàng)建它時(shí)被注入到拼寫檢查器中排龄。
// 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(adj.任意的) 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).
依賴注入模式非常簡(jiǎn)單,許多程序員在不知道其名稱的情況下使用了多年翎朱。雖然拼寫檢查器示例只有一個(gè)資源(字典)橄维,但是依賴注入可以處理任意數(shù)量的資源和任意依賴路徑尺铣。它保持了不可變性(Item-17),因此多個(gè)客戶端可以共享依賴對(duì)象(假設(shè)客戶端需要相同的底層資源)争舞。依賴注入同樣適用于構(gòu)造函數(shù)凛忿、靜態(tài)工廠(Item-1)和構(gòu)建器(Item-2)。
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:
這種模式的一個(gè)有用變體是將資源工廠傳遞給構(gòu)造函數(shù)竞川。工廠是一個(gè)對(duì)象店溢,可以反復(fù)調(diào)用它來(lái)創(chuàng)建類型的實(shí)例。這樣的工廠體現(xiàn)了工廠方法模式 [Gamma95]流译。Java 8 中引入的 Supplier<T>
非常適合表示工廠逞怨。在輸入中接受 Supplier<T>
的方法通常應(yīng)該使用有界通配符類型(Item-31)來(lái)約束工廠的類型參數(shù),以允許客戶端傳入創(chuàng)建指定類型的任何子類型的工廠福澡。例如,這里有一個(gè)生產(chǎn)瓷磚方法驹马,每塊瓷磚都使用客戶提供的工廠來(lái)制作馬賽克:
Mosaic create(Supplier<? extends Tile> tileFactory) { ... }
Although dependency injection greatly improves flexibility and testability, it can clutter up(使雜亂) large projects, which typically(adv.通常) 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(n.手冊(cè)革砸;adj.手工的) dependency injection are trivially(adv.繁瑣地) adapted for(適用于) use by these frameworks.
盡管依賴注入極大地提高了靈活性和可測(cè)試性,但它可能會(huì)使大型項(xiàng)目變得混亂糯累,這些項(xiàng)目通常包含數(shù)千個(gè)依賴項(xiàng)算利。通過(guò)使用依賴注入框架(如 Dagger、Guice 或 Spring)泳姐,幾乎可以消除這種混亂效拭。這些框架的使用超出了本書的范圍,但是請(qǐng)注意胖秒,為手動(dòng)依賴注入而設(shè)計(jì)的 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.
總之,不要使用單例或靜態(tài)實(shí)用工具類來(lái)實(shí)現(xiàn)依賴于一個(gè)或多個(gè)底層資源的類阎肝,這些資源的行為會(huì)影響類的行為挤渔,也不要讓類直接創(chuàng)建這些資源。相反风题,將創(chuàng)建它們的資源或工廠傳遞給構(gòu)造函數(shù)(或靜態(tài)工廠或構(gòu)建器)判导。這種操作稱為依賴注入,它將大大增強(qiáng)類的靈活性沛硅、可重用性和可測(cè)試性眼刃。