Skip to content

面向对象编程:Mixin(混入)——代码复用利器

什么是 Mixin?

Mixin 是一种在多个类层次结构中复用代码的方式,无需使用继承。

基本 Mixin

dart
mixin Flyable {
  void fly() {
    print('飞行中!');
  }
}

mixin Swimmable {
  void swim() {
    print('游泳中!');
  }
}

class Bird with Flyable {}

class Fish with Swimmable {}

class Duck with Flyable, Swimmable {}

void main() {
  Bird().fly();        // 飞行中!
  Fish().swim();       // 游泳中!
  
  var duck = Duck();
  duck.fly();          // 飞行中!
  duck.swim();         // 游泳中!
}

带状态的 Mixin

dart
mixin Musical {
  bool isPlaying = false;
  
  void play() {
    isPlaying = true;
    print('播放音乐');
  }
  
  void stop() {
    isPlaying = false;
    print('音乐停止');
  }
}

class Smartphone with Musical {
  String brand;
  
  Smartphone(this.brand);
}

void main() {
  var phone = Smartphone('iPhone');
  phone.play();   // 播放音乐
  phone.stop();   // 音乐停止
}

on 子句的 Mixin

限制哪些类可以使用 mixin:

dart
class Animal {
  void breathe() => print('呼吸');
}

mixin Flyable on Animal {
  void fly() {
    breathe();  // 可以使用 Animal 方法
    print('飞行');
  }
}

class Bird extends Animal with Flyable {}

// class Plane with Flyable {}  // 错误:Plane 必须扩展 Animal

void main() {
  Bird().fly();
}

完整示例

dart
abstract class Vehicle {
  void move();
}

mixin Electric {
  int batteryLevel = 100;
  
  void charge() {
    batteryLevel = 100;
    print('充满电');
  }
  
  void useBattery(int amount) {
    batteryLevel -= amount;
    print('电量:$batteryLevel%');
  }
}

mixin GPS {
  void navigate(String destination) {
    print('导航到 $destination');
  }
}

class ElectricCar extends Vehicle with Electric, GPS {
  @override
  void move() {
    useBattery(10);
    print('汽车正在行驶');
  }
}

void main() {
  var car = ElectricCar();
  car.move();                    // 电量:90%,汽车正在行驶
  car.navigate('家');            // 导航到 家
  car.charge();                  // 充满电
}

下一步