在dart语言中有两种方式可以创建工厂模式:一是直接使用顶层的方法。二是使用工厂模式的构造方法。
使用一个图形工厂创建圆和方举例,基本代码如下:
import 'dart:math';
abstract class Shape {
num get area;
}
class Circle implements Shape {
final num radius;
Circle(this.radius);
num get area => pi * pow(radius, 2);
}
class Square implements Shape {
final num side;
Square(this.side);
num get area => pow(side, 2);
}
main() {
final circle = Circle(2);
final square = Square(2);
print(circle.area);
print(square.area);
}
方式一、采用顶层方法
Shape shapeFactory(String type) {
if (type == 'circle') return Circle(2);
if (type == 'square') return Square(2);
throw 'Can\'t create $type.';
}
main() {
final circle = shapeFactory('circle');
final square = shapeFactory('square');
print(circle.area);
print(square.area);
}
方式二、创建一个工厂模式的构造方法
abstract class Shape {
factory Shape(String type) {
if (type == 'circle') return Circle(2);
if (type == 'square') return Square(2);
throw 'Can\'t create $type.';
}
num get area;
}
main() {
final circle = Shape('circle');
final square = Shape('square');
print(circle.area);
print(square.area);
}
网友评论