Dart, 클래스에 기능 추가하기(mixin)
글. 수알치 오상문
Mxin(믹스인)은 여러 클래스 계층 구조에서 클래스 코드를 재사용하는 방법입니다. Mixin을 사용하려면 with 키워드 다음에 하나 이상의 Mixin 이름을 사용하십시오. 다음 예제는 Mixiin을 사용하는 두 클래스를 보여줍니다.
class Musician extends Performer with Musical {
// ···
}
class Maestro extends Person with Musical, Aggressive, Demented {
Maestro(String maestroName) {
name = maestroName; canConduct = true;
}
}
Mixin을 구현하려면 Object를 확장하고 생성자를 선언하지 않는 클래스를 만듭니다. Mixin을 일반 클래스로 사용하려면 class 대신 mixin 키워드를 사용합니다.
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을 사용할 수있는 유형을 제한하고 싶을 수 있습니다. 다음 예에서 볼 수 있듯이 on 키워드를 사용하여 필수 슈퍼 클래스를 지정하여 Mixin의 사용을 제한 할 수 있습니다.
class Musician { // ... } mixin MusicalPerformer on Musician {
// ...
}
class SingerDancer extends Musician with MusicalPerformer {
// ...
}
앞 예에서 Musician 클래스를 확장하거나 구현하는 클래스만 MusicalPerformer Mixin을 사용할 수 있습니다. SingerDancer는 Musician을 확장하기 때문에 SingerDancer는 MusicalPerformer에서 Mixin 할 수 있습니다.
<이상>
'Dart' 카테고리의 다른 글
Dart, 제너릭(Generic) (0) | 2021.06.17 |
---|---|
Dart, 클래스 변수와 메서드 (0) | 2021.06.17 |
Dart, 열거형 (Enumerated type) (0) | 2021.06.17 |
Dart, 클래스 class 확장 (0) | 2021.06.17 |
Dart, 메서드(메소드) (0) | 2021.06.17 |