[英]Scala: Dependency Injection
Given the following scenario 鉴于以下情况
abstract class Animal {/***/}
class Dog(s : String) extends Animal {/***/}
class Cat(s :String) extends Animal {/***/}
class C() {
val animal: Animal = new Dog(name)
private def name = "name for animal that C knows how to calculate"
}
How can I provide an Animal instance to C, instead of being C the one who creates it? 如何向C提供Animal实例,而不是创建它的C?
It is possible to do something like 有可能做类似的事情
class B(f : String => Animal) {
val animal: Animal = f(name)
private def name = "name for animal that B knows how to calculate"
}
which then allows me 然后允许我
val bWithDog = new B((name: String) => new Dog(name))
val bWithCat = new B((name: String) => new Cat(name))
which is my goal But is this a clean solution? 这是我的目标但这是一个干净的解决方案吗? Or it does not make sense to provide an Animal to C, since only C knows how to calculate its name?
或者将Animal提供给C是没有意义的,因为只有C知道如何计算它的名字?
class C(val animal: Animal) {
private def name = "name for animal that C knows how to calculate"
}
new C(new Dog("fiddo"))
What's wrong with constructor arguments? 构造函数参数有什么问题?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.