0%

Mixins of Dart

Dart里的Mixin

一开始以为只是简单的代码混入,感觉还蛮好用。

但是多个Mixin如果有相同的函数或变量混入了如何解决?

Mixins in Dart work by creating a new class that layers the implementation of
the mixin on top of a superclass to create a new class - it is not “on the side “ but “on top” of the superclass, so there is no ambiguity in how to resolve lookups.

- Lasse R. H. Nielsen on StackOverflow.

以下的代码,实际上继承链为Disposable->A->B->AB。

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
abstract class Disposable {
void dispose() {
print('Disposable');
}
}

mixin A on Disposable {
@override
void dispose() {
super.dispose();
print('A');
}
}

mixin B on Disposable {
@override
void dispose() {
super.dispose();
print('B');
}
}

final class AB extends Disposable with A,B {
@override
void dispose() {
super.dispose();
print('AB');
}
}


void main() {
AB().dispose();
}