2012-11-10 29 views
1

這是我實現斯卡拉蛋糕模式早期的嘗試之一:如何改善這種嘗試在蛋糕圖案

trait dbConfig { 
    val m: Model = ??? 
} 

trait testDB extends dbConfig { 
    override val m = new Model(Database.forURL("jdbc:h2:mem:testdb", driver = "org.h2.Driver")) 
    m.cleanDB 
} 

trait productionDB extends dbConfig { 
    override val m = new Model(Database.forURL("jdbc:postgresql:silly:productionDB", driver = "org.postgresql.Driver")) 
} 

trait SillySystem extends HttpService with dbConfig { 
.... 
// System logic 
.... 
} 

這將允許我使用我的服務這樣的測試時:

class TestService extends SillySystem with testDB { 
..... 
} 

而且這樣生產:

class ProductionService extends SillySystem with productionDB { 
..... 
} 

這工作,但我在做正確嗎?

+1

你可以離開了'M'成員抽象的特質'VAL L:Model',而且也沒有必要'override'在subtrait –

回答

3

這可能是有益的,使DbConfig抽象和使用defsince一個可以覆蓋defvallazy val,而不是倒過來。

SillySystem is not a DbConfig,所以使用依賴注入而不是繼承。

trait DbConfig { 
    def m: Model // abstract 
} 

trait TestDB extends DbConfig { 
    // you can override def with val 
    val m = new Model(Database.forURL("jdbc:h2:mem:testdb", driver = "org.h2.Driver")) 
    m.cleanDB 
} 

trait ProductionDB extends DbConfig { 
    val m = new Model(Database.forURL("jdbc:postgresql:silly:productionDB", driver = "org.postgresql.Driver")) 
} 

trait SillySystem extends HttpService { 
    this: DbConfig => // self-type. SillySystem is not a DbConfig, but it can use methods of DbConfig. 
.... 
// System logic 
.... 
} 

val testService = new SillySystem with TestDB 

val productionService = new SillySystem with ProductionDB 

val wrongService1 = new SillySystem // error: trait SillySystem is abstract; cannot be instantiated 
val wrongService2 = new SillySystem with DbConfig // error: object creation impossible, since method m in trait DbConfig of type => Model is not defined 

val correctService = new SillySystem with DbConfig { val m = new Model(...) } // correct 
+0

你,先生,是我的英雄!你剛剛提到了我不喜歡我早期嘗試的兩件事情。我不知道一個關於def可以被val覆蓋的def,我知道我需要一個類型化的自引用,但我不確定如何使用它。謝謝! – Jack

+0

自我類型不是免費的,但是,在編譯時需要支付一定的代價(閱讀:可能最好不要瘋狂,灑「自我:Foo與Bar and Bar」=>遍佈各處) – virtualeyes