scala - 蛋糕图案 : How to share an instance?

标签 scala cake-pattern

我的 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 trait 放在 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/

相关文章:

scala - StatusDescription=此请求无权使用此权限执行此操作

scala - 提升 - 未找到代码片段失败方法

java - 来自数组的 Scala HashMap

scala - 蛋糕图案和类型

Scala 蛋糕模式和依赖冲突

Akka 和蛋糕图案

c# - 为什么 .NET 的 Scala 编译器会忽略 val 的含义?

scala - Scala 是否与 Haskell 的 undefined 等价?

scala - 在 Scala 中使用 self 类型时如何保持单一责任?

scala - 如何使用 Scala 的蛋糕模式来实现机器人腿?