본문 바로가기
Flutter

Flutter 2Team Dart Mixins

by DSC PKNU 2021. 3. 1.

[Dart] Mixins

이런 문법은 처음본다.... 그래서 정리를 해보려고한다.

 

우선 Mixins람 무었일까? 

 

클래스를 상속하지 않고 상속한 것 처럼 메소드를 사용할 수 있는 클래스이다.

 

이런 문구를 언제사용할 수 있을까? 최근 oop에서는 다중상속을 많이 지원하지 않는다. 이는 죽음의 다이아몬드라는 문제 때문인데 다트 또한 다중 상속을 지원하지 않는다. 

class Animal{
	void move(){
    	print('move Postion');
    }
}

class Fish extends Animal{
  @override
  void move(){
    super.move();
    print('by Swim');
  }
}

class Bird extends Animal{
  @override
  void move(){
    super.move();
    print('by Flying');
  }
}

 

만약 상속을 통해 위와 같이 코드를 구성했는데 오리의 경우 육해공 모두 되어서 다중상속을 통해서 코드를 표현할 수 없다. 따라서 이럴 때 mixin을 통해 편리하게 다중상속과 같은 효과를 지원하고 있다. 

 

class Animal{
	void move(){
    	print('move Postion');
    }
}

mixin canSwim{
	void swim(){
    	print('move Postion by Swim');
    }
}

mixin canFly{
	void fly(){
    	print('move Postion by Fly');
    }
}

mixin canRun{
	void run(){
    	print('move Postion by Run');
    }
}


class Duck extends Animal with canFly, canRun, canSwim{
	@override
    void move(){
    	swim();
      fly();
      run();
    }
}

void main(){
  Duck().move();
}

 

위를 보면 간단하게 사용법을 알 수 있다. 일반적으로는 with이라는 키워드와 함께 사용하며 함수를 호출하여 사용할 수 있다. 



출처: https://hoony-gunputer.tistory.com/entry/Dart-Mixins [후니의 컴퓨터]

'Flutter' 카테고리의 다른 글

Flutter 2Team Firebase 데이터 저장하기 & [Dart] Stream  (0) 2021.03.01
Flutter 2Team 서버리스  (0) 2021.03.01
Flutter 2Team Animation  (0) 2021.03.01
Flutter 2Team Dart Static  (0) 2021.03.01
[Flutter-1Team] 섹션 13 - 비동기  (0) 2021.01.27