这是我实现 Scala Cake Pattern 的早期尝试之一:
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 {
.....
}
这行得通,但我做得对吗?