我的 Scala 项目中有一个配置组件。

显然,我不想拥有多个此组件的实例。我正在使用蛋糕图案,但我不确定如何调整它以满足我的要求:

// Library
// =================================================
trait ConfigComp {

  trait Config {
    def get(k: String): String
  }

  def config: Config
}

trait QueueComp {
  self: ConfigComp =>

  class Queue {
    val key = config.get("some-key")
  }

  lazy val queue = new Queue
}

// Application
// =================================================

trait MyConfig extends ConfigComp {

  lazy val config = new Config {
    println("INITIALIZING CONFIG")

    def get(k: String) = "value"
  }
}

object Frontend extends QueueComp with MyConfig
object Backend  extends QueueComp with MyConfig

Frontend.queue.key
Backend.queue.key

打印:
INITIALIZING CONFIG
INITIALIZING CONFIG

如何让蛋糕模式共享 Config 的匿名实例?

最佳答案

像这样的东西?

// Library
// =================================================
trait Config {
  def get(k: String): String
}

trait ConfigComp {
  def config: Config
}

trait QueueComp {
  self: ConfigComp =>
  class Queue {
    val key = config.get("some-key")
  }
  lazy val queue = new Queue
}

// Application
// =================================================

object SingleConfig extends ConfigComp {
  lazy val config = new Config {
    println("INITIALIZING CONFIG")
    def get(k: String) = "value"
  }
}

object Frontend extends QueueComp with ConfigComp {
  val config = SingleConfig.config
}
object Backend  extends QueueComp with ConfigComp {
  val config = SingleConfig.config
}

Frontend.queue.key
Backend.queue.key

如果您的 Config 特征放在 ConfigComp 内,我无法解决这些类型错误:
error: type mismatch;
 found   : MyConfig.Config
 required: Frontend.Config
    (which expands to)  Frontend.Config
                override def config = MyConfig.config

error: type mismatch;
 found   : MyConfig.Config
 required: Backend.Config
    (which expands to)  Backend.Config
                override def config = MyConfig.config

关于scala - 蛋糕图案 : How to share an instance?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14652986/

10-11 06:19