mixin小记

2023-07-06  本文已影响0人  jancywen

Dart 是不支持多继承的,但是它支持 mixin,简单来讲 mixin 可以 “组合” 多个类,如果多个mixin 中有同名方法,with 时,会默认使用最后面的 mixin 的,mixin 方法中可以通过 super 关键字调用之前 mixin 或类中的方法。

abstract class Configure {
  config() {}
}

mixin One on Configure {
  @override
  config() {
    print("up one");
    super.config();
    print("one");
  }
}

mixin Two on Configure {
  @override
  config() {
    print("up two");
    super.config();
    print("two");
  }
}

mixin Three on Configure {
  @override
  config() {
    print('up three');
    super.config();
    print('three');
  }
}

class Zero extends Configure with One, Two, Three {
  @override
  config() {
    super.config();
  }
}

void main(List<String> args) {
  Zero zero = Zero();
  zero.config();
}

// $dart test1.dart
// up three
// up two
// up one
// one
// two
// three
上一篇 下一篇

猜你喜欢

热点阅读