【发布时间】:2013-10-08 09:08:12
【问题描述】:
在 Head First Design Patterns 中,有人提到您应该编写接口而不是实现,但是代码示例的最后一部分让我感到困惑。如何在运行时分配对象的具体实现是一个更好的设计?
这是否意味着将对象的实例化放在使用超类型的类的方法中更好? (一种专门将对象返回给超类的变量的方法)
//Programming to an implementation would be:
Dog d = new Dog();
d.bark();
//Programming to an interface/supertype would be:
Animal animal = new Dog();
animal.makeSound();
//Even better is assigning the concrete implementation at runtime: (says the book)
a = getAnimal();
animal.makeSound();
【问题讨论】:
-
使用后者,您可以使用依赖注入,这样您就可以更轻松地单独测试每个类。您看不到您的简单示例的价值,但是一旦您开始从事复杂的多类项目,收益可能是巨大的。
-
持久性无知:stackoverflow.com/questions/1974735/…,减少依赖/耦合:stackoverflow.com/questions/4541952/…,可测试性:stackoverflow.com/questions/8578104/…。请注意,可测试性示例使用的是 IOC 容器注入,而不是构造函数注入。
标签: java design-patterns runtime