Dart-试图了解“工厂”构造函数的价值 [英] Dart - Trying to understand the value of 'factory' constructor
问题描述
如果我正确理解:
"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
,我被问到为什么要为Animal加上额外的代码?
So if I am correct with all this, I am led to ask why the extra code for Animal?
如果您打算为动物使用工厂构造函数(仅创建猫),为什么不只拥有Cat?
If you intend on using a factory constructor for animal, which creates only cats, why not just have a Cat class with the required methods/properties?
或者,动物类的目的是使用上面的工厂构造函数,真的是专门为Cat类设计的接口吗?
Or, is the purpose of the Animal class with a factory constructor like above, really an interface specifically designed for Cat class only?
推荐答案
我认为工厂中的问题 code>。
您的代码最初是错误的。
Your code initially was wrong.
看下面的代码并得出结论
Look at this code and make your conclusions.
Locomotive locomotive = new SomethingWithSmokeFromChimney();
现在看下面的代码。
Plant plant = new SomethingWithSmokeFromChimney();
您错误地认为地球上的所有动物(甚至是狗)都是猫。
You mistakenly believe that all animals on the earth (even the dogs) are cats.
Cat cat = new Animal();
如果您要这样做。
Cat cat = new Animal();
Dog dog = new Animal();
然后(如果我正确理解你的话),你也想要这个。
Then (if I correctly understand you) you also want this.
// Cat cat = new Animal();
// Dog dog = new Animal();
Dog dog = new Cat();
PS
相同的错误结论,但没有工厂
。
The same wrong conclusions but without factory
.
void main() {
Cat cat = new Animal();
Dog dog = new Animal();
}
class Animal {
}
class Cat implements Animal {
}
class Dog implements Animal {
}
但是此代码(取决于文档)可能被认为是正确的。 / p>
But this code (depending on documenation) may be considered correct.
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 {
}
抽象类的工厂构造函数可以(默认)返回该抽象类的一些默认实现
The factory constructor of the abstract class can return (by default) some default implementation of this abstract class.
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;
}
}
这篇关于Dart-试图了解“工厂”构造函数的价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!