假设我有具体的类 Cat、Dog 和 Parrot,以及以下接口:
class HasGuid {
HasGuid.fromId(String id);
}
Run Code Online (Sandbox Code Playgroud)
我的目标是保证 Cat、Dog 和 Parrot 都有一个fromId命名构造函数。所以,我可以拨打这样的电话:
Cat.fromId("Whiskers") =returns> [A Future<Cat> object with id "Whiskers"]
Dog.fromId("Fido") =returns> [A Future<Dog> object with id "Fido"]
Parrot.fromId("Polly") =returns> [A Future<Parrot> object with id "Poly"]
Run Code Online (Sandbox Code Playgroud)
fromId正在通过网络进行呼叫,因此我将其作为Future. 我基本上想要一份合同,规定任何混合/扩展/实现/任何类的HasGuid类都将具有fromId. fromId类中的位置T将接受一个身份字符串并返回一个Future<T>.
简而言之,您不能强制子类实现特定的命名构造函数...您所能做的就是强制子类确保子类调用命名构造函数。
以下面为例...
class Animal {
String name;
Animal.fromName(this.name);
}
class Dog extends Animal {
Dog.withName(String name) : super.fromName(name);
}
Run Code Online (Sandbox Code Playgroud)
请注意以下事项...
Animal没有零参数构造函数。super.fromName()构造函数,Dog你会得到一个编译错误The superclass 'Animal' doesn't have a zero argument constructor.
Run Code Online (Sandbox Code Playgroud)
Dog必须调用fromName()构造函数...但它不必同样调用其命名构造函数。在这种情况下,请注意它被称为withName().小智 3
无法保证构造函数。
实例方法的接口(实现)保证。超类(extends)或Mixins(with)也保证实例方法,而不是构造函数。
构造函数返回它自己的类型,而不是 Future。
所以它们都应该有一个静态方法或类,但不能保证。
| 归档时间: |
|
| 查看次数: |
4060 次 |
| 最近记录: |