我有一个scala特征如下 -
trait Mytrait {
def saveData : Boolean = {
//make database calls to store
true
}
def getData : Integer = {
//get data from database
return i
}
}
现在我听说过蛋糕模式,但我无法弄清楚如何应用蛋糕模式来模拟这样的特征。
有人能指出如何做到这一点吗?
答案 0 :(得分:0)
你会这样做:
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和你的特质中形成'layers'或'cake'。
这只是一个简单的例子,您可以扩展所涉及的组件数量,有多个MyTrait实现,您希望在不同的环境下使用它们等等。例如,参见Dependency Injection in Scala: Extending the Cake Pattern