很多类会依赖一个或者多个底层资源。例如,拼写检查工具依赖词典。将这样的类实现为静态工具类的做法不少见。
1.不恰当的使用了静态工具类-----不够灵活且难以测试
public class Person {
private String name;
private Integer age;
// 设为公有构造器
public Person(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
public class SpellCheck {
private static final Person dictionary = new Person("姓名字典");
// 不可实例化
private SpellCheck(Person dictionary) {
System.out.println("这是"+dictionary);
}
}
这是姓名字典
Process finished with exit code 0
2.不恰当的使用singleton----不够灵活且难以测试
public class SpellCheck {
private final Person dictionary = new Person("姓名字典");
// 不可实例化
private SpellCheck(String dictionary) {
System.out.println("这是"+dictionary);
}
public static SpellCheck INSTANCE= new SpellCheck("姓名字典");
}
这是姓名字典
com.example.alibaba.test.SpellCheck@705d8b85
Disconnected from the target VM, address: '127.0.0.1:50847', transport: 'socket'
Process finished with exit code 0
以上两种方法都不能令人满意,因为他们都假定只有一个词典值得使用。
最佳方法就是,在创建新实例时将资源传入构造器。
public class SpellCheck {
private final Person dictionary;
public SpellCheck(Person dictionary) {
this.dictionary = dictionary;
}
public static void main(String[] args) {
Person person = new Person();
person.setName("姓名字典");
SpellCheck spellCheck = new SpellCheck(person);
System.out.println("这是"+spellCheck.dictionary.toString());
}
}
这是姓名字典
Process finished with exit code 0
总而言之,对于依赖一个或多个底层资源,而且资源的行为会对其行为造成影响的类,不要使用singleton或者静态类来实现,也不要让该类直接创建这些资源。相反,应该将资源或创建资源的工厂传递给构造器(静态工厂,或生成器)。这种做法,也就是所谓的依赖注入,将极大的提升类的灵活性、复用性和可测试性。
那么问题来了,依赖注入又有哪些方式???欢迎留言!
Tips:所有内容开源且不追加任何条件,看完后觉得内容不错,点个赞不为过吧!