【发布时间】:2017-01-13 10:32:18
【问题描述】:
我正在使用特征作为模块来构建我的代码,我可以根据需要互换插入它们,类似于以下示例:
trait Module1 { def method1 = "method1" }
trait Module2 { def method2 = "method2" }
abstract class BaseClass {
def doWork: Unit
}
class ClassImpl extends BaseClass with Module1 with Module2 {
def doWork: Unit = {
println(method1)
println(method2)
}
}
但是,我的一些模块依赖于一些配置变量(用户定义的、运行时参数),如果它们是类,我会将它们作为构造函数参数传递。由于特征不接受参数,我的想法是使用结构类型:
trait Module1 {
this: {
val config1: Int
val config2: Int
} =>
def method1 = s"method1 c1=$config1 c2=$config2"
}
trait Module2 { def method2 = "method2" }
abstract class BaseClass {
def doWork: Unit
}
case class Config(c1: Int, c2: Int)
class ClassImpl(config: Config) extends BaseClass with Module1 with Module2 {
protected val config1 = config.c1
protected val config2 = config.c2
def doWork: Unit = {
println(method1)
println(method2)
}
}
这是配置我的模块的好策略还是有更好的策略?
【问题讨论】:
标签: scala