避免在Dart中继承类 [英] Avoid inheritance of class in Dart
问题描述
在Dart中是否有避免继承的方法?我正在寻找
Is there a way to avoid inheritance in Dart? I'm looking for something like
final class MyJavaClass {
...
}
推荐答案
不直接,不.
您可以编写带有私有构造函数的类,并通过静态方法访问它们:
You could write a class with private constructors and access them via static methods:
class MyFinalClass {
MyFinalClass._ctor1() {}
MyFinalClass._ctor2(String param1, String param2) {}
static MyFinalClass getInstance() {
return new MyFinalClass._ctor1();
}
static MyFinalClass getInstanceWithParams(String param1, String param2) {
return new MyFinalClass._ctor2(param1, param2);
}
}
但这有多个问题:
- 同一库中的类仍然可以对其进行子类化-Dart中的可见性适用于库,而不是单个类.
- 很多代码,随构造函数的数量而扩展.
- 它引入了许多静态方法,所有这些方法都必须以不同的方式命名.
- 当然,您不能使用
new
关键字在类库之外实例化该类. - 这仅防止扩展类.仍然可以实现最终"类.
- Classes inside the same library can still subclass it - visibility in Dart applies to libraries, not single classes.
- It's a lot of code, scaling with the amount of constructors.
- It introduces lots of static methods, which all have to be named differently.
- And of course, you can't instantiate the class outside its library with the
new
keyword. - This only prevents extension of a class. Implementing the "final" class is still possible.
这些功能最终有很多缺点.由您决定是否真的值得.
Ultimately, these are quite a few drawbacks for this feature. It's up to you to decide if it is really worth it.
编辑
与我之前写的相反,工厂构造函数也可以工作,消除了无法使用 new
关键字实例化"的缺点.
Contrary to what I have written before, factory constructors would also work, eliminating the "unable to instantiate with new
keyword" drawback.
class MyFinalClass {
factory MyFinalClass.ctor1() {}
factory MyFinalClass.ctor2(String param1, String param2) {}
void method1() {}
void method2() {}
}
另外,为了说明为什么不能实现最终类的能力是一个大问题:
Also, to illustrate why the ability to implement the not-so-final class is a big problem:
class Sub implements MyFinalClass {
MyFinalClass _d;
Sub.ctor1() {
_d = new MyFinalClass.ctor1();
}
Sub.ctor2(String p1, String p2) {
_d = new MyFinalClass.ctor2(p1,p2);
}
void method1() => _d.method1();
void method2() {
// do something completely different
}
}
此伪子类化也可以与静态方法变体一起使用.
This pseudo-subclassing would work with the static method variant as well.
这篇关于避免在Dart中继承类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!