3

我的 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

4

2 回答 2

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

如果您的Configtrait 放在里面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
于 2013-02-01T21:37:25.000 回答
1

正如 om-nom-nom 所提到的,您正在寻找使用单例,因此应该MyConfig使用config在对象中初始化的 a 。对于第二个问题,在您的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

于 2013-02-01T21:41:35.900 回答