简体   繁体   中英

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?

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?

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM