蛋糕模式:如何共享实例?

时间:2013-02-01 18:45:07

标签: 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的匿名实例?

2 个答案:

答案 0 :(得分:3)

这样的东西?

// 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

答案 1 :(得分:1)

正如提到的om-nom-nom,你正在寻找使用单例,因此应该使MyConfig使用在对象中初始化的config。对于第二个问题,在gist中,出现以下错误:

[error] overriding method config in trait ConfigComp of type => MyConfig.this.Config;
[error]  lazy value config has incompatible type
[error]   lazy val config = MyConfig.config
[error]            ^
[error] one error found

基本上告诉你确切的问题。 MyConfig.this.Config不等于对象MyConfig.this.Config。为了更清楚,让我们将代码更改为以下内容:

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

trait MyConfig extends ConfigComp {
  lazy val config = MyConfigSingleton.config
}

此处为MyConfig.this.Config != MyConfigSingleton.this.Config

类型