Dart接口的实现

Dart 语言并没有提供 interface 关键字,但是每一个类都隐式地定义了一个接口。

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
33
34
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);
}

class CircleMock implements Circle {
num area;
num radius;
}

main() {
final circle = Shape('circle');
final square = Shape('square');
print(circle.area);
print(square.area);
}

扩展 Circle 类,增加一个 CircleMock:

1
class CircleMock implements Circle {}

将会看到一个 “Missing concrete implementations” 的错误,添加两个实例变量 area 和 radius 即可修复这个问题

1
2
3
4
class CircleMock implements Circle {
num area;
num radius;
}

Powered by AppBlog.CN     浙ICP备14037229号

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

访客数 : | 访问量 :