2017-12-05 15 views
0

projectAScalaのケーキのパターンとマルチ

trait DBProvider 
trait DBTableNamesProvider 
trait DefaultDBProvider extends DBProvider 
trait DefaultTableNames extends DBTableNamesProvider 

trait MyService extends DBProvider with DBTableNamesProvider 

object MyService { 
    def apply() = new MyService with DefaultDBProvider with DefaultTableNames {} 
} 

私はMyServiceで

PROJECTA(コモンに依存しているを構築したい瓶としてcommon-projectへの参照を持っていますプロジェクト):

object MyOtherApp { 
    trait MyOtherTableName extends DBTableNamesProvider 
    val MyCustomService = MyService() with MyOtherTableName // will not compile how to reuse the module's MyService() with another implementation of one of the traits? 
} 

上記は、私はちょうどMyServiceで()の建設を呼び出し、依存関係の一部を上書きすることはできませんコンパイルされません。

これは私がやりたいことですが、別のプロジェクトからMyService()の工場構築がMyProjectATableNamesの独自の実装で適用されることは、scalaでも可能ですか?コードの繰り返しがない場合の推奨方法は何ですか?

答えて

1
val MyCustomService = new MyService() with MyOtherTableName 

はあなたにもDefaultDBProviderDefaultTableNamesを継承したい場合は、あなたにも明示的に列挙するかだろう

を動作するはずです共通ライブラリ:

trait DefaultService extends MyService with DefaultDBProvider with DefaultTableNames 
0

MyService()はもうオブジェクト型ではないため、そのような構築型をオーバーライドすることはできません。だからあなたのコードを再利用するために、あなたは

object MyService { 
    def apply() = new ConfiguredMyService 
} 

を宣言することができます最初のアプリで

class ConfiguredMyService extends DefaultDBProvider with DefaultTableNames 

のようなクラスを作成しますと第二

val MyCustomService = new ConfiguredMyService with MyOtherTableName 

注意に:今日では、ケーキのパターンがあります反パターンと見なされているので、依存性注入をチェックアウトすることをお勧めします。

val MyCustomService = new MyService() with MyOtherTableName with DefaultDBProvider with DefaultTableNames 

または中間形質を作成する:

+0

「MyService」は特性であり、確かにex匿名でそれを好む傾向がある。また、ケーキのパターンには何も問題はありません。ただし、Playを好きなブロガーの意見には、多分あります。 – Dima

関連する問題