假设您有一个类 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) }
}
当你想扩展Foo
asBar
和时会发生什么Baz
,如果两个子类都需要有相同的工厂方法?您不想将伴生对象复制Foo
为伴生对象Bar
和伴生对象Baz
,那么使工厂方法“通用”的正确方法是什么?