第5条:优先考虑依赖注入来连接资源

很多类会依赖一个或者多个底层资源。例如,拼写检查工具依赖词典。将这样的类实现为静态工具类的做法不少见。

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:所有内容开源且不追加任何条件,看完后觉得内容不错,点个赞不为过吧!

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值