Dart创建工厂模式
定义Shape形状类,并输出其面积
Dart 支持抽象类,可以在一个文本中定义多个类
dart.math 是一个 Dart 核心库,其余的还有诸如 dart:core,dart:async,dart:convert 和 dart:collection 这样的核心库
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);
}
创建一个顶层的方法
import 'dart:math';
abstract class Shape {
num get area;
}
Shape shapeFactory(String type) {
if (type == 'circle') return Circle(2);
if (type == 'square') return Square(2);
throw 'Can\'t create $type.';
}
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() {
try {
print(shapeFactory('circle').area);
print(shapeFactory('square').area);
} catch (err) {
print(err);
}
}
创建一个工厂模式的构造方法
使用 Dart 的 factory 关键字来创建一个工厂模式的构造方法
import 'dart:math';
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;
}
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 = Shape('circle');
final square = Shape('square');
print(circle.area);
print(square.area);
}
版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/03/16/dart-create-factory-mode/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。
THE END
0
二维码
打赏
海报
Dart创建工厂模式
定义Shape形状类,并输出其面积
Dart 支持抽象类,可以在一个文本中定义多个类
dart.math 是一个 Dart 核心库,其余的还有诸如 dart:core,dart:async,dart:c……
文章目录
关闭
共有 0 条评论