你会这样做:
trait Mytrait { this: DbConnectionFactory => // Require this trait to be mixed with a DbConnectionFactory
def saveData : Boolean = {
val connection = getConnection // Supplied by DbConnectionFactory 'layer'
//use DB connection to make database calls to store
true
}
def getData : Integer = {
val connection = getConnection // Supplied by DbConnectionFactory 'layer'
val i: Integer = ... // use DB connection to get data from database
return i
}
}
trait DbConnection
trait DbConnectionFactory {
def getConnection: DbConnection
}
// --- for prod:
class ProdDbConnection extends DbConnectionFactory {
// Set up conn to prod Db - say, an Oracle DB instance
def getConnection: DbConnection = ???
} // or interpose a connection pooling implementation over a set of these, or whatever
val myProdDbWorker = new ProdDbConnection with Mytrait
// --- for test:
class MockDbConnection extends DbConnectionFactory {
// Set up mock conn
def getConnection: DbConnection = ???
}
val myTestDbWorker = new MockDbConnection with Mytrait
您从合适的 DbConnectionFactory 和您的特征形成“层”或“蛋糕”的地方。
这只是一个简单的示例,您可以扩展所涉及的组件数量,拥有多个 MyTrait 实现,您希望在不同的情况下使用它们等。参见,例如Scala 中的依赖注入:扩展蛋糕模式