LoginSignup
0
0

More than 1 year has passed since last update.

[Dart]mixinとは

Posted at

mixinとは

classで共通する機能を、継承を使ってmixさせる。

具体例

導入

Animalクラスを作り、継承を使用してBirdFishクラスを作成する。

void main() {
  Fish().move();
  Bird().move();
}

class Animal {
  void move() {
    print('change position.');
  }
}

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

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

一見、BirdFishクラスを美しく定義できているように見える。
しかし、泳ぎと飛ぶが両方できるアヒルクラスを作る際には上記の書き方では問題が出てくる。

BirdFishクラスのどちらを継承させるのが適切か不明となる。

class Duck extends Bird {} //Birdを継承させるべき?
class Duck extends Fish {} //Fishを継承させるべき?

mixin

そこで、mixinの登場!!

void main() {
  Duck().swim();
  Duck().fly();
}

...

mixin CanSwim {
  void swim() {
    print('can swim.');
  }
}

mixin CanFly {
  void fly() {
    print('can fly.');
  }
}
  
class Duck with CanSwim, CanFly {
}

mixinによって共通する機能をどちらも継承することができる。

まとめ

mixinで共通する機能を分離させて、withで継承させる。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0