使用工厂模式在 Scala 中防止 class 实例化
Preventing a class instantiation in Scala using Factory Pattern
假设我在 Scala 中定义了以下 class:
class ClassA(val n: Int) {
...
}
我想使用工厂模式将此 class 实例限制为只有 n 在 5 到 10 之间的实例。例如,如果我写这样的东西:
val a = new ClassA(11)
这会引发异常并显示相应的错误消息,或者至少 returns null 或其他内容。我怎样才能实现这种行为?
更新:
可以在 java with Factory pattern 中实现。
更新2:
这个问题似乎得到了回答 here,不过标题很冗长。我调整了标题和内容以保存被删除的问题,原因有两个:1)这个例子中的例子很简洁,2)@Chris Martin 提供的答案简要解释了通过使用在 Scala 中可以达到工厂模式的方式同伴 Objects.
在 Scala 中编写工厂的常规方法是在伴随对象上定义一个 apply
方法。
这是一个使用 Either
的示例(因为 null
在 Scala 中使用 never/rarely,并且异常很丑陋):
class A private (n: Int) {
override def toString = s"A($n)"
}
object A {
def apply(n: Int): Either[String, A] =
if (n < 5) Left("Too small")
else if (n > 10) Left("Too large")
else Right(new A(n))
}
A(4) // Left(Too small)
A(5) // Right(A(5))
A(11) // Left(Too large)
这与您引用的 Java 示例基本相同。 A
构造函数是私有的,所以class只能通过工厂方法实例化。
假设我在 Scala 中定义了以下 class:
class ClassA(val n: Int) {
...
}
我想使用工厂模式将此 class 实例限制为只有 n 在 5 到 10 之间的实例。例如,如果我写这样的东西:
val a = new ClassA(11)
这会引发异常并显示相应的错误消息,或者至少 returns null 或其他内容。我怎样才能实现这种行为?
更新:
可以在 java with Factory pattern 中实现。
更新2:
这个问题似乎得到了回答 here,不过标题很冗长。我调整了标题和内容以保存被删除的问题,原因有两个:1)这个例子中的例子很简洁,2)@Chris Martin 提供的答案简要解释了通过使用在 Scala 中可以达到工厂模式的方式同伴 Objects.
在 Scala 中编写工厂的常规方法是在伴随对象上定义一个 apply
方法。
这是一个使用 Either
的示例(因为 null
在 Scala 中使用 never/rarely,并且异常很丑陋):
class A private (n: Int) {
override def toString = s"A($n)"
}
object A {
def apply(n: Int): Either[String, A] =
if (n < 5) Left("Too small")
else if (n > 10) Left("Too large")
else Right(new A(n))
}
A(4) // Left(Too small)
A(5) // Right(A(5))
A(11) // Left(Too large)
这与您引用的 Java 示例基本相同。 A
构造函数是私有的,所以class只能通过工厂方法实例化。