0

我有一个 scala 特征如下 -

trait Mytrait {
   def saveData : Boolean = {
      //make database calls to store
      true
   }
    def getData : Integer = {
        //get data from database
        return i
    }

}

现在我听说过蛋糕图案,但我无法弄清楚如何应用蛋糕图案来模拟这样的特征。

谁能指出如何做到这一点?

4

1 回答 1

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 和您的特征形成“层”或“蛋糕”的地方。

这只是一个简单的示例,您可以扩展所涉及的组件数量,拥有多个 MyTrait 实现,您希望在不同的情况下使用它们等。参见,例如Scala 中的依赖注入:扩展蛋糕模式

于 2013-07-30T23:53:01.707 回答