首页 > 解决方案 > 如何编写一个可以添加任意数量的类的mixin,同时可以访问某些保证变量?

问题描述

如何编写一个可以添加任意数量的类的mixin,同时可以访问某些保证变量?

例如,这里的答案是可以的,但是如果希望 Comedian mixin 不仅对 Person 类可用,而且对任何具有int age变量的类可用怎么办?

标签: dart

解决方案


答案是通过一个界面。接口基本上是一个抽象类,您可以通过 implements 而不是 extends 关键字使用它。虽然一个类只能扩展一个父类,但它可以实现任意数量的接口。

这是一个具体的例子:

void main() {

  final person = Bob();
  print(person.age);
  print(person.ageInside);
//   output will be 31, 13
  
  final yogiBear = Yogi();
  print(yogiBear.age);
  print(yogiBear.ageInside);
//   output will be 40, 22
}

abstract class MortalCreature {
  int age;
  MortalCreature(this.age);
}

mixin Comedian on MortalCreature {
  // no need to declare age variable here, it finds it through `on`
  int get ageInside {
    return age - 18;
  }
}

class Person implements MortalCreature {
  int age;
  int get ageInside {
    return age;
  }
  Person(this.age);
}

class Bear implements MortalCreature {
  int age;
  Bear(this.age);
}

class Bob extends Person with Comedian {
  Bob() : super(31);
}

class Yogi extends Bear with Comedian {
  Yogi() : super(40);
}

推荐阅读