これを行う1つの方法は、抽象ファクトリ関数に依存する一般的なメソッドを含むmixin特性を定義することです。次に、コンパニオンオブジェクトは、そのようなミックスインを拡張し、対応するインスタンスを作成する特定の方法を実装するだけです。
例:あなたは、ターゲットクラス階層の特定のメソッドにアクセスする必要がある場合
trait FooFactory[T] {
def make(s:String, i:Int): T
def apply(s:String):T = make(s, 0)
def apply(i:Int):T = make("", i)
}
class A(s:String = "", i:Int = 0) {
def foo:String = s+i
override def toString() :String = s"[$foo]"
}
// object A {
// def apply(a:String): A = { new A(s=a)}
// def apply(a:Int): A = { new A(i=a)}
// }
object A extends FooFactory[A] {
def make(s:String, i:Int) = new A(s,i)
}
class B(s:String = "") extends A(s,-1){
override def foo:String = s+":"+super.foo
}
// object B {
// def apply(a:String):B = { new B(a)}
// def apply(a:Int):B = { new B(a.toString)}
// }
object B extends FooFactory[B] {
def make(s:String, i:Int) = new B(s)
}
、あなたはそのサブタイプのそのクラスにタイプを制限することができます。
trait FooFactory[T <: A] {
def make(s:String, i:Int): T
def apply(s:String): T = make(s, 0).someAMethod()
}
は、クラスAとBのコンストラクタのシグネチャは同じですか? – Eduardo
@Edurardo:Aがパラメータをtrueに設定するため、Bに1つのパラメータがないことを除いて、ほとんど同じです。 – prosseek
'A'や' B'インスタンスが必要な時はどのように区別しますか? – maasg