有什么区别:
class A {}
class B with A{}
和
mixin A{}
class B with A{}
?
在 Dart 中,一个类只能
extend
另一个类。但它可以 implement
或 mixin
任意数量。
问题是,当你扩展一个类时,你继承了它的所有属性、方法和构造函数。当你实现一个类时,如果你只添加你还没有的方法/属性,你可以简单地继续你的代码。如果您要实现抽象方法,则需要实际实现它。现在,mixin 就像扩展类,混合它们的类是它们的子类,以及扩展和实现,但它没有构造函数。
mixin 的实际想法是,您可以向任何类添加功能,并且它们不必扩展另一个类。这就是为什么他们通常只做简单的事情。
//normal class u can create constructors create objects from it and all that good jazz
class Foo {
final int a;
Foo(this.a);
void someMethod() {}
}
//mixin is like a container than hold some functionalities that you want to mix with an existing class
mixin Bar {
void add() {}
}
// this class extends Foo to inherent some goodness but i need a functionality that is not directly related to parent child relationship so i mix it with Bar
class Baz extends Foo with Bar {
Baz(super.a);
void myMethod() {
// i have access to add function here
add();
}
}
// mixin class act like both
mixin class AnotherClass {
AnotherClass();
}