scala "factory" 用于从字符串创建案例对象的设计模式

scala "factory" design pattern for creating case object from string

我是 scala 的新手,正在寻找 "scala" 方法来创建正确的大小写 class(符合特征),该大小写由外部源从字符串枚举中获取。由于源是外部的,因此应该验证输入是否正确,并且给定有效输入将返回正确的大小写 class。我假设这是一个"factory",return是给定特征

的可选案例class

示例:

trait ProcessingMechanism
case object PMv1 extends ProcessingMechanism
case object PMv2 extends ProcessingMechanism
case object PMv3 extends ProcessingMechanism
...
...

我想要一个工厂return正确的处理机制

object ProcessingMechanismFactory {
   ... switch on the input string to return the correct mechanism???
   ... is there a simple way to do this?
}

无需借助宏或外部库,您可以做一些像这样简单的事情:

object ProcessingMechanism {
  def unapply(str: String): Option[ProcessingMechanism] = str match {
    case "V1" => Some(PMv1)
    case "V2" => Some(PMv2)
    // ...
    case _ => None
  }
}

// to use it:
def methodAcceptingExternalInput(processingMethod: String) = processingMethod match {
  case ProcessingMethod(pm) => // do something with pm whose type is ProcessingMethod
}
// or simply:
val ProcessingMethod(pm) = externalString

正如问题评论中所建议的,最好将特征标记为 sealed