blu*_*e10 6 factory scala initialization enforcement
让我们假设我们有一个特征T.实现以下目标的最佳方法是:
T应该被迫提供允许无参数初始化的可能性T,即我们可能必须强制执行可配置工厂.A的T)的逻辑/数据应集中处理/存储,但应在工厂和工厂都可用A.我看到实现这个(大约)的最简单/最简单的方法是为工厂添加特征并链接T到这个工厂:
trait T {
val factory: TFactory
}
trait TFactory {
def build(): T
val description: String // example for logic/data that only depend on the parameters
}
// example implementation:
class A(val factory: AFactory, paramA: Int, paramB: Int, paramC: Int) extends T
class AFactory(paramA: Int, paramB: Int, paramC: Int) extends TFactory {
def build = new A(this, paramA, paramB, paramC)
val description = f"$paramA $paramB $paramC"
}
Run Code Online (Sandbox Code Playgroud)
显然,这并没有真正"强制"实施工厂(只要有可用的替代实现),显然可以生成A链接到"错误"的实例化TFactory.我也不喜欢这种方法是重复初始化参数.我经常创建另一个类AParams,它再次包装所有参数(例如,以便于添加新参数).因此,我最终得到了三个类,对于这个简单的问题,imho是很多样板.
我的问题是,是否存在(可能完全)不同的方法,它实现了相同的主要目标,但更简洁?
我不太确定我是否完全理解了您的要求,但是您对这种行为有何看法?
trait TFactory{
def build():T
val description:String
}
trait T extends TFactory
//can't declare A without build and not make it abstract
class A(paramA: Int, paramB: Int, paramC: Int) extends T {
def build = new A(paramA, paramB, paramC)
val description = f"$paramA $paramB $paramC"
}
val a1 = new A(1, 4, 5)
val a2 = a1.build()
//We can give ourselves as a factory to something that expects TFactory
val factory:TFactory = a1
val a_new = factory.build()
//More likely we can just give our build method
def func(f: ()=>T) = {
val new_t = f()
new_t
}
val a_newer = func(a1.build)
println(a1 +": " + a1.description)
println(a2 +": " + a2.description)
println(a_new +": " + a_new.description)
println(a_newer +": " + a_newer.description)
Run Code Online (Sandbox Code Playgroud)
输出:
Main$$anon$1$A@69267649: 1 4 5
Main$$anon$1$A@69b1fbf4: 1 4 5
Main$$anon$1$A@24148662: 1 4 5
Main$$anon$1$A@3f829e6f: 1 4 5
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
193 次 |
| 最近记录: |