我有一个类, Base
这是一个抽象类,定义为:
abstract class Base() {}
我想从这个基类创建一些派生类:
class A : Base() {}
class B : Base() {}
class C : Base() {}
我希望能够调用一个常用函数 create
,它执行一些初始化工作并返回指定的派生类(例如 A
) . 例如,以下类似的东西是理想的:
val a = A.create() // `a` now holds an instance of `A`.
val b = B.create()
val c = C.create()
最初我试图在抽象类中使用一个伴随对象作为一种静态函数:
abstract class Base {
companion object {
fun create() : Base {
// Do some initialization and return the derived class
// of the object. Obviously I can't return `Base` as I've
// indicated above since it is an abstract class. This is
// what I'm confused about: How do I return a copy of the
// _derived_ class here? Is this impossible? I think it
// might be...
return Base() // <-- This doesn't work. What should be returned?
}
}
}
然后在派生类中:
class A : Base() {
companion object {
fun create() : A = Base.create()
}
}
这不会返回抽象类 Base
的实例 . 有没有一种简单的方法来完成 var a = A.create()
范式? create
的代码在派生类中是相同的,所以我想避免在我创建的每个类中重新创建功能 .
2 回答
如果初始化逻辑相同并且基于
Base
类中指定的功能,您也可以这样做:可能会工作,但可能需要使用不安全的反射 . 这取决于你在
create
中究竟想要做什么......更好的做法是将类之间的任何不同之处作为一个函数传递,例如: