代码之家  ›  专栏  ›  技术社区  ›  Jas

在cake模式中,如何从客户端替换一些没有直接关系的内部实现?

  •  2
  • Jas  · 技术社区  · 7 年前

    公共项目中的模块代码通过jar共享,我希望更改内部依赖关系 在编译时

    trait MyTableNames
    trait MyDAO extends MyTableNames
    trait ActorService { 
      def send(actorMessage: Any) = println("sending message... will reach some Actor and then from actor to DAO")
    }
    trait MyActor extends MyDAO
    object SaveUserActorMessage
    
    trait MyService extends ActorService {
      def addUser() = send(SaveUserActorMessage) // Not aware of dao just sends a message so service is disconnected from DAO.
    }
    

    通过共享jar使用公共项目的不同服务器代码 使用此服务的客户端代码仅创建服务。 问题是我需要“注入”MyTableNames的其他一些实现

    来自重复使用上述公共项目的不同项目:

    trait MyOwnTableNames extends MyTableNames 
    class MyCustomService extends MyService {
      def someOtherAddUser() = addUser() // How do I tell the DAO which the service does not have a direct reference to, to use MyOwnTableNames, in compile time right now as a client code, I only have reference to MyService.  In addition MyService has no direct relation to MyDAO it's only has a relation to ActorService which has no direct relation to DAO only the end actor which processes the message has a reference to DAO.
    }
    

    请注意:这个例子看起来并不“漂亮”,也不是严格的蛋糕模式,我必须这样做,以便我可以将其压缩为几行代码,底线是我的客户端代码引用服务并对服务执行操作,服务然后向参与者发送消息,最终参与者使用DAO,我的问题是,最后的DAO试图引用我要替换的表名。我使用干净的scala代码,没有DI框架,我更喜欢避免隐式,如果可能的话,只使用cake模式。

    1 回复  |  直到 7 年前
        1
  •  0
  •   badcook    7 年前

    你可以依靠Scala的线性化来正确地排序特征,并且只需简单地执行

    class MyCustomService extends MyService with MyOwnTableNames
    

    这里有一个小警告。如果有什么 extend s MyTableNames 使用某些值 我的表名 在一个 val ,由于类初始化排序问题,您可以获得NPE。要解决这个问题,您必须使用 lazy val def .