Scala Cake Pattern and Dependency Collisions

前端 未结 5 2718
情深已故
情深已故 2021-02-20 05:08

I\'m trying to implement dependency injection in Scala with the Cake Pattern, but am running into dependency collisions. Since I could not find a detailed example with such depe

5条回答
  •  悲哀的现实
    2021-02-20 05:22

    Seems to be the known "robot legs" problem. You need to construct two legs of a robot, however you need to supply two different feet to them.

    How to use the cake pattern to have both common dependencies and separate?

    Let's have L1 <- A, B1; L2 <- A, B2. And you want to have Main <- L1, L2, A.

    To have separate dependencies we need two instances of smaller cakes, parameterized with common dependencies.

    trait LegCommon { def a:A}
    trait Bdep { def b:B }
    class L(val common:LegCommon) extends Bdep { 
      import common._
      // declarations of Leg. Have both A and B.
    }
    trait B1module extends Bdep {
      val b = new B1
    }
    trait B2module extends Bdep {
      def b = new B2
    }
    

    In Main we'll have common part in cake and two legs:

    trait Main extends LegCommon {
      val l1 = new L(this) with B1module
      val l2 = new L(this) with B2module
      val a = new A
    }
    

提交回复
热议问题