如果我理解正确的话:
"A factory constructor affords an abstract class to be
instantiated by another class, despite being abstract."
例如:
abstract class Animal {
String makeNoise(String sound);
String chooseColor(String color);
factory Animal() => new Cat();
}
class Cat implements Animal {
String makeNoise(String noise) => noise;
String chooseColor(color) => color;
}
上面的内容允许我这样做:
Cat cat = new Animal();
var catSound = cat.makeNoise('Meow');
var catColor = cat.chooseColor('black');
print(catSound); // Meow
它也阻止我这样做:
class Dog implements Animal {
int age;
String makeNoise(String noise) => noise;
String chooseColor(color) => color;
}
Dog dog = new Animal(); // <-- Not allowed because of the factory constructor
因此,如果我对所有这些都是正确的,我就会问为什么要为动物添加额外的代码?
如果您打算使用动物的工厂构造函数,它只创建猫,为什么不直接使用具有所需方法/属性的 Cat 类呢?
或者,是带有像上面这样的工厂构造函数的 Animal 类的目的,真的是专门为 Cat 类设计的接口吗?
我不认为问题出在factory
.
您的代码最初是错误的。
看看这段代码并得出你的结论。
Locomotive locomotive = new SomethingWithSmokeFromChimney();
现在看看这段代码。
Plant plant = new SomethingWithSmokeFromChimney();
你错误地认为地球上所有的动物(甚至狗)都是猫。
Cat cat = new Animal();
如果你想要这个。
Cat cat = new Animal();
Dog dog = new Animal();
那么(如果我正确理解你的话)你也想要这个。
// Cat cat = new Animal();
// Dog dog = new Animal();
Dog dog = new Cat();
P.S.
同样的错误结论但没有factory
.
void main() {
Cat cat = new Animal();
Dog dog = new Animal();
}
class Animal {
}
class Cat implements Animal {
}
class Dog implements Animal {
}
但这段代码(取决于文档)可能被认为是正确的。
void main() {
Cat cat = new Animal("cat");
Dog dog = new Animal("dog");
}
abstract class Animal {
factory Animal(String type) {
switch(type) {
case "cat":
return new Cat();
case "dog":
return new Dog();
default:
throw "The '$type' is not an animal";
}
}
}
class Cat implements Animal {
}
class Dog implements Animal {
}
抽象类的工厂构造函数可以(默认)返回该抽象类的一些默认实现。
abstract class Future<T> {
factory Future(computation()) {
_Future result = new _Future<T>();
Timer.run(() {
try {
result._complete(computation());
} catch (e, s) {
result._completeError(e, s);
}
});
return result;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)