Mix:混合
In: 进入,加入
Mixin: 混入
mixin 声明 属于dart 2.1 加入的特性。以前版本通常使用abstract class代替。
abstract class 不能被实例化,声明时可以有方法实现。
mixin功能:给一个类添加特性
声明方式: 使用mixin 声明一个class,并且不声明构造方法。
mixin Musical {
bool canPlayPiano = false;
bool canCompose = false;
bool canConduct = false;
void entertainMe() {
if (canPlayPiano) {
print('Playing piano');
} else if (canConduct) {
print('Waving hands');
} else {
print('Humming to self');
}
}
}
To use a mixin, use the with keyword followed by one or more mixin names.
要使用一个mixin,使用with关键字,在它后面添加一个或多个mixin类的名字。
与implements 的区别:
使用implements 的子类,必须全部实现或者重写类接口的类方法。
使用with,可以重写,也可以不重写。
mixin Person {
void work(int age) {
if (age > 18 && age < 60) {
print("need work");
} else {
print("not need work");
}
}
void breath(){
print("Yes");
}
}
class Children with Person {
void work(int age){
print(" child not need work");
}
}
main() {
Children child = new Children();
child.work(8);
child.breath();
}
- CONSOLE
child not need work
Yes
不重写的话,调用接口方法。
好处:
当很多类implements一个接口时,必须实现其全部方法。使用mixin with后,可以选择实现。
网友评论