我有单身人士:
class MySing private (var1: SomeType) { ... }
object MySing {
@volatile
private var instance: Option[MySing] = None
def apply(var1: SomeType): Option[MySing] = {
if (instance.isEmpty) {
this.synchronized {
if (instance.isEmpty) instance = Some(new MySing(var1))
}
}
instance
}
}
因此,每当我想获得它的实例时,我必须使用get或模式匹配
MySing(myVar1) match {
case Some(x) => ...
case None =>
}
或
MySing(myVar1).get
即使Scala鼓励使用Option,在我的情况下不使用它来摆脱我上面展示的无聊冗余操作也不合理吗?
object MySing {
@volatile
private var instance: MySing = null
def apply(var1: SomeType): MySing = {
if (instance == null) {
this.synchronized {
if (instance == null) instance = new MySing(var1)
}
}
instance
}
}
答案 0 :(得分:2)
返回Option[MySing]
意味着您不能从None
返回值(即返回apply
),但我不知道这有多大意义。你总是从申请中返回一个实例,所以你可以在返回类型中获得Option
,如下所示
class MySing private (val var1: String)
object MySing {
@volatile
private var instance: Option[MySing] = None
def apply(var1: String): MySing = {
instance getOrElse {
this.synchronized {
instance.getOrElse {
instance = Some(new MySing(var1))
instance.get
}
}
}
}
}
用法示例
scala> val x = MySing("hello")
x: MySing = MySing@232b0a52
scala> x.var1
res0: String = hello
scala> val y = MySing("hola")
y: MySing = MySing@232b0a52
scala> y.var1
res1: String = hello // are you sure this is sensible?
然而,它仍然看起来有点难看:你正在创建一个带参数的单例,因此忽略了第一次调用后传递给apply
方法的每个参数。啊!
您可能想重新考虑您的设计(并忘记null
)