在蛋糕模式中抽象数据库客户端

时间:2014-01-21 07:38:03

标签: scala initialization polymorphism client cake-pattern

我正在尝试使用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特性实现中吗?

1 个答案:

答案 0 :(得分: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
}