混入
混入是一种定义代码的方式,这些代码可以在多个类层次结构中复用。它们旨在大量提供成员实现。
要使用混入,请使用 with
关键字,后跟一个或多个混入名称。以下示例展示了使用(或继承自)混入的两个类
class Musician extends Performer with Musical {
// ···
}
class Maestro extends Person with Musical, Aggressive, Demented {
Maestro(String maestroName) {
name = maestroName;
canConduct = true;
}
}
要定义混入,请使用 mixin
声明。在极少数情况下,当你需要同时定义混入和类时,可以使用 mixin class
声明。
混入和混入类不能有 extends
子句,并且不得声明任何生成式构造函数。
例如
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');
}
}
}
指定混入可以调用的自身成员
#有时混入依赖于能够调用方法或访问字段,但不能自行定义这些成员(因为混入不能使用构造函数参数来实例化自己的字段)。
以下各节介绍了确保混入的任何子类定义混入行为所依赖的任何成员的不同策略。
在混入中定义抽象成员
#在混入中声明抽象方法会强制使用该混入的任何类型定义其行为所依赖的抽象方法。
mixin Musician {
void playInstrument(String instrumentName); // Abstract method.
void playPiano() {
playInstrument('Piano');
}
void playFlute() {
playInstrument('Flute');
}
}
class Virtuoso with Musician {
@override
void playInstrument(String instrumentName) { // Subclass must define.
print('Plays the $instrumentName beautifully');
}
}
在混入的子类中访问状态
#声明抽象成员还允许你通过调用在混入中定义为抽象的 getter 来访问混入子类上的状态
/// Can be applied to any type with a [name] property and provides an
/// implementation of [hashCode] and operator `==` in terms of it.
mixin NameIdentity {
String get name;
@override
int get hashCode => name.hashCode;
@override
bool operator ==(other) => other is NameIdentity && name == other.name;
}
class Person with NameIdentity {
final String name;
Person(this.name);
}
实现接口
#与将混入声明为抽象类似,在混入上添加 implements
子句但未实际实现接口,也将确保为混入定义所有成员依赖项。
abstract interface class Tuner {
void tuneInstrument();
}
mixin Guitarist implements Tuner {
void playSong() {
tuneInstrument();
print('Strums guitar majestically.');
}
}
class PunkRocker with Guitarist {
@override
void tuneInstrument() {
print("Don't bother, being out of tune is punk rock.");
}
}
使用 on
子句声明超类
#on
子句用于定义 super
调用所解析的类型。因此,你只应在混入内部需要进行 super
调用时使用它。
on
子句强制使用混入的任何类也是 on
子句中类型的子类。如果混入依赖于超类中的成员,这可以确保在使用混入的地方这些成员是可用的
class Musician {
musicianMethod() {
print('Playing music!');
}
}
mixin MusicalPerformer on Musician {
performerMethod() {
print('Performing music!');
super.musicianMethod();
}
}
class SingerDancer extends Musician with MusicalPerformer { }
main() {
SingerDancer().performerMethod();
}
在此示例中,只有扩展或实现 Musician
类的类才能使用混入 MusicalPerformer
。因为 SingerDancer
扩展了 Musician
,所以 SingerDancer
可以混入 MusicalPerformer
。
class
、mixin
还是 mixin class
?
#mixin
声明定义一个混入。class
声明定义一个类。mixin class
声明定义一个类,该类可以用作普通类,也可以用作混入,具有相同的名称和类型。
mixin class Musician {
// ...
}
class Novice with Musician { // Use Musician as a mixin
// ...
}
class Novice extends Musician { // Use Musician as a class
// ...
}
适用于类或混入的任何限制也适用于混入类
- 混入不能有
extends
或with
子句,因此mixin class
也不能有。 - 类不能有
on
子句,因此mixin class
也不能有。