2

我正在尝试使用 Cake 模式为 SearchService 创建一个抽象。这是我目前拥有的:

trait SearchServiceComponent{
  val searchService:SearchService

  trait SearchService{
      def searchForSomething(..):List[String]
      def updateIndex(..):Boolean
  } 
}

假设我有一个 DbSearchServiceComponent 和 LuceneSearchServiceComponent 如下:

trait DbSearchServiceComponent extends SearchServiceComponent{
   class DbSearchService extends SearchService{
           //Initialize the db client
           //Implement all the trait methods
   }
}

相似地...

trait LuceneSearchServiceComponent extends SearchServiceComponent{
  class LuceneSearchService extends SearchService{
     //Initialize the lucene client
     //Implement all the trait methods
  }
}

我对上述代码段的问题是

我已经在服务实现中初始化了 lucene 客户端和 db 客户端的实例。

理想情况下,我想“混合”一个“客户端”基本类型,它可以是 Db 客户端或 Lucene 客户端,但我对如何在此处注入多态客户端类型感到非常困惑。

有人能指出我如何能够重构代码,以便我可以将不同版本的客户端注入到我的 SearchService 特征的实现中吗?

4

1 回答 1

2

不确定我是否正确解释了您的问题,但这就是您可以为此使用蛋糕模式的方式:

trait SearchServiceComponent {
  val searchService: SearchService

  trait SearchService {
    def searchForSomething(...): List[String]
    def updateIndex(...): Boolean
  } 
}

trait DbSearchServiceComponent extends SearchServiceComponent {
   override val searchService = new SearchService {
    // Initialize client, implement methods
   }
}

trait trait LuceneSearchServiceComponent extends SearchServiceComponent {
   override val searchService = new SearchService {
    // Initialize client, implement methods
   }
}

并在实例化时:

val myLucenceApp = new Whatever with LuceneSearchServiceComponent
val myDbApp = new Whatever with DbSearchServiceComponent

哪里Whatever通常是类似的东西

class Whatever { this: SearchServiceComponent =>
   // ... use `searchService` and do lots of other things
}
于 2014-01-21T08:54:23.417 回答