Scala

一番シンプルなDI

DI難しい、ので出来る人に教えてもらった。ので自分ようでメモ

// Interface
trait TestInterface {
  def print(s: String): Unit
}

// Injection用Interface
trait UsesTestInterface {
  protected val test: TestInterface
}

// implimentation1
object Test1 extends TestInterface {
  override def print(s: String): Unit = {
    println(s"test1 = $s")
  }
}
// Injection1
trait MixInTest1 extends UsesTestInterface {
  override protected val test: TestInterface = Test1
}

// implimentation2
object Test2 extends TestInterface {
  override def print(s: String): Unit = {
    println(s"test2 = $s")
  }
}
// Injection2
trait MixInTest2 extends UsesTestInterface {
  override protected val test: TestInterface = Test2
}
trait Test extends UsesTestInterface {
  val i: String
  def run(s: String): Unit = {
    test.print(s"$s$i")
  }
}

// Injection & implimentation
class Test1 extends Test with MixInTest1 {
  override val i: String = "1"
}
// Injection & implimentation
class Test2 extends Test with MixInTest2 {
  override val i: String = "2"
}

(new Test1).run("hoge")
(new Test2).run("hoge")

結果

test1 = hoge1
test2 = hoge2