Mixin
은 생성자가 없는 클래스
를 의미합니다.mixin
키워드를 사용하여 Mixin 선언합니다.with
키워드를 사용하여 원하는 클래스에서 Mixin 을 가져다 씁니다.// Mixins
//// `Mixin` 은 `생성자가 없는 클래스`를 의미합니다.
//// 클래스에 프로퍼티, 메소드를 추가할 때 사용합니다.
//// 다른 클래스에 여러번 사용할 수 있는 것이 장점입니다.
//// 절대로 부모/자식 클래스 관계가 되지않습니다.
//// 단지, 필요한 프로퍼티, 메소드만 뺐어옵니다.
//// Flutter 와 Flutter 플로그인들을 사용할 때 많이 접하게 됩니다.
mixin Strong {
final double strengthLevel = 1500.99;
}
mixin QuickRunner {
void runQuick() {
print('ruuuuun!');
}
}
mixin Tall {
final double height = 1.99;
}
enum Team { red, blue }
class Human {
final String name;
int xp;
Human({
required this.name,
required this.xp,
});
void sayHello() {
print('hi my name is $name');
}
}
// extends, with 키워드 동시 사용 가능
class Player extends Human with Strong, QuickRunner, Tall {
final Team team;
Player({
required this.team,
required String name,
required super.xp,
}) : super(name: name);
void sayHello() {
super.sayHello();
print('and I play for $team');
}
}
// Mixin 다중 사용 예시
class Sprinter with QuickRunner {}
class Wrestler with Strong, Tall {}
class Giant with Tall {}
void main() {
var player = Player(
team: Team.red,
name: 'Park',
xp: 0,
);
player.sayHello();
player.runQuick();
print('height: ${player.height}');
print('strength level: ${player.strengthLevel}');
}
학습 중에 작성된 내용이므로 잘못되거나 부족한 내용이 있을 수 있습니다.