Dart创建工厂模式

定义Shape形状类,并输出其面积

Dart 支持抽象类,可以在一个文本中定义多个类
dart.math 是一个 Dart 核心库,其余的还有诸如 dart:core,dart:async,dart:convert 和 dart:collection 这样的核心库

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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);
}

创建一个顶层的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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 关键字来创建一个工厂模式的构造方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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);
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :