Dart中的Mixins:如何使用它们

时间:2018-09-02 00:17:54

标签: dart mixins

因此,我正在尝试创建一个简单的小程序,在其中使用mixins。我想代表一个书店,有两个产品(书,书包)..但是我想让抽象类自上而下(Com)定义可以应用于所有产品(对象)的方法,而无需更改单个类。但是,我不知道如何实现这一点。该方法可以像跟踪书店中是否有一本书一样简单。

这是我当前的代码:

abstract class Com {
not sure not sure
}


class Product extends Object with Com {
String name;
double price;
Product(this.name, this.price);
}

class Bag extends Product {
String typeofb;
Bag(name, price, this.typeofb) :super(name, price);
}

class Book extends Product {

String author;
String title;
Book(name, price, this.author, this.title):super(name, price);
}

void main() {
var b = new Book('Best Book Ever', 29.99,'Ed Baller & Eleanor Bigwig','Best 
Book Ever');

 }

1 个答案:

答案 0 :(得分:1)

Dart mixin当前只是一袋成员,您可以在另一个类定义的顶部复制这些成员。 它类似于实现继承(extends),只不过您扩展了超类,但扩展了 with 混合。由于您只能拥有一个超类,因此mixins允许您以不同的方式(并且受更多限制)共享不需要超类了解您的方法的实现。

您在此处描述的内容听起来像可以使用通用超类进行处理一样。只需将方法放在Product上,并让BagBook都可以扩展该类。如果您没有不需要混合方法的Product子类,则没有理由不将它们不包括在Product类中。

如果您确实想使用mixin,则可以编写如下内容:

abstract class PriceMixin {
  String get sku;
  int get price => backend.lookupPriceBySku(sku);
}
abstract class Product {
  final String sku;
  Product(this.sku); 
}
class Book extends Product with PriceMixin {  
  final String title;
  Product(String sku, this.title) : super(sku);
}
class Bag extends Product with PriceMixin {
  final String brand;
  Product(String sku, this.brand) : super(sku);
}
class Brochure extends Product { // No PriceMixin since brochures are free.
  final String name;
  Brochure(String sku, this.name) : super(sku);
}