Scala:我应该使用什么模式为Int,Double和String创建一个公共抽象?

时间:2015-09-29 13:02:09

标签: scala design-patterns

我需要重构整个系统,我想了解如何处理类型问题的建议。

我有这种情况:我使用PMML(基本上是带有数据模式规范的XML)和HBase(不保留数据类型模式的柱状存储)。我需要在操作系统中的值时匹配这两者。所以我需要一个抽象来处理可能属于我系统的所有可能的数据类型。现在我有Int,Double和String。

对于每种类型,我需要能够定义解析器(用于HBase),编写器和一组定义为高阶函数的操作((T,T)=>T)

现在我尝试使用由trait MyValue[T]MyValueInt extends MyValue[Int]扩展的MyValueDouble extends MyValue[Double]来做到这一点。我可以定义一个像List [(MyValue,MyValue)=> MyValue]这样的操作列表,但每次都必须将它与每个案例进行匹配,并在类型系统中创建了许多其他问题。

我需要的是一个很好的抽象来模拟这些值只能是Int,Double和Strings的事实,以创建这些值的列表并能够使用通用逻辑处理这些值,直到我需要提取实际价值并将其应用于某项业务。

1 个答案:

答案 0 :(得分:2)

类型类看起来像是解决问题的方法。

// Define the behaviors you want your types to support
trait Parser[T] {
  def parse(s: String): T
}

trait Writer[T] {
  def write(value: T): Unit
}

trait Operations[T] {
  def add(a: T, b: T): T
  def multiply(a: T, b: T): T
}

// Implement the behaviors for each of the types you need
object IntStuff {
  implicit object IntParser extends Parser[Int] {
    override def parse(s: String): Int = Integer.valueOf(s)
  }
  implicit object IntWriter extends Writer[Int] {
    override def write(value: Int): Unit = println(value)
  }
  implicit object IntOperations extends Operations[Int] {
    override def add(a: Int, b: Int): Int = a + b
    override def multiply(a: Int, b: Int): Int = a * b
  }
}

// Define an algorithm on the type, put a context bound on it.
// This would make sure that the operations you need are supported for type `T`.

def writeSum[T: Parser : Writer : Operations](xs: String*): Unit = {
  // Bring the implementation from implicit scope
  val parser = implicitly[Parser[T]]

  // Use the implementation
  val values = xs.map(parser.parse)
  if (values.nonEmpty) {
    val writer = implicitly[Writer[T]]
    val operations = implicitly[Operations[T]]

    val sum = values.reduce(operations.add)
    writer.write(sum)
  }
}

// Bring the implementation to the implicit scope
import IntStuff._

// Enjoy :)    
writeSum[Int]("1", "2", "3")