0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

一番シンプルなDI

Last updated at Posted at 2018-01-31

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
0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?