使用工厂模式防止Scala中的类实例化 [英] Preventing a class instantiation in Scala using Factory Pattern

查看:113
本文介绍了使用工厂模式防止Scala中的类实例化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在Scala中定义了以下类:

class ClassA(val n: Int) {
   ...
}

我想使用Factory Pattern将此类实例限制为只有 n 在5到10之间的那些实例.例如,万一我写的是这样的话:

val a = new ClassA(11)

这会引发带有适当错误消息的异常,或者至少它返回null或其他内容.我该如何实现这种行为?

更新:

可以在Java 中使用工厂模式来实现这一点. /p>

Update2:

该问题似乎已得到回答解决方案

在Scala中编写工厂的常规方法是在伴随对象上定义apply方法.

这是使用Either的示例(因为null在Scala中从未使用过,很少见,并且异常很难看):

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构造函数是私有的,因此只能通过工厂方法实例化该类.

Suppose that I have the following class defined in Scala:

class ClassA(val n: Int) {
   ...
}

I want to limit this class instances to only those that have n between 5 to 10 using Factory Pattern. For example, In case I write something like:

val a = new ClassA(11)

This raises an exception with an appropriate error message, or at least it returns null or something. How can I achieve this behaviour?

Update:

It is possible to achieve this in java with Factory pattern.

Update2:

This questions seems to be answered here, notably with a verbose title though. I tweak the title and content to save the question being deleted, because of two reasons: 1) The example in this one is concise, 2) the provided answer by @Chris Martin explains briefly the way Factory pattern can be reached in Scala by Using Companion Objects.

解决方案

The conventional way to write a factory in Scala is to define an apply method on the companion object.

Here's an example using Either (because null is never/rarely used in Scala, and exceptions are ugly):

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)

This is the essentially the same as the Java example you referenced. The A constructor is private, so the class can only be instantiated via the factory method.

这篇关于使用工厂模式防止Scala中的类实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆