2

假设您有一个类 Foo,它是对某种文本文件的抽象,以及一个带有简化 Foo 创建的工厂方法的伴随对象:

class Foo(val lines : Seq[String], filePath : String) { ... }

object Foo {
  def apply(file : File) : Foo = { new Foo(scala.io.Source.fromFile(file, "ISO-8859-1").mkString.split("\n").toList, file.getPath }
  def apply(file : String) : Foo = { apply(new File(file) }
}

当你想扩展FooasBar和时会发生什么Baz,如果两个子类都需要有相同的工厂方法?您不想将伴生对象复制Foo为伴生对象Bar和伴生对象Baz,那么使工厂方法“通用”的正确方法是什么?

4

1 回答 1

1

您可以执行以下操作:

trait FooFactory[T <: Foo] {
   def apply(file : File) : T = //to be implement in your Baz and Bar class
   def apply(file : String) : T = { apply(new File(file) }   //shared method, no need to implement in subclassing classes

}


//example for Bar implementation------------------------------

class Bar extends Foo {
     // any specific Bar code here
}

object Bar extends FooFactory[Bar] {
  def apply(file : File) : Bar = { new Bar(scala.io.Source.fromFile(file, "ISO-8859-1").mkString.split("\n").toList, file.getPath }
} 
于 2014-04-06T16:09:27.740 回答