The Pragmatic Programmer中第 143 页的代码片段如下:
public class Colada {
private Blender myBlender;
private Vector myStuff;
public Colada() {
myBlender = new Blender();
myStuff = new Vector();
}
private doSomething() {
myBlender.addIngredients(myStuff.elements());
}
}
这符合得墨忒耳定律/最少知识原则。
将其替换为使用依赖注入的以下内容是否更可取,是否有任何警告?
public class Colada throws IllegalArgumentException {
private Blender myBlender;
private Vector myStuff;
public Colada(Blender blender, Vector stuff) {
if (null == blender) {
throw new IllegalArgumentException()
} else {
myBlender = blender;
}
if (null == stuff) {
throw new IllegalArgumentException()
} else {
myStuff = stuff;
}
}
public static Colada createDefaultInstance() {
Blender blender = new Blender();
Vector stuff = new Vector();
return new Colada(blender, stuff);
}
private doSomething() {
myBlender.addIngredients(myStuff.elements());
}
}