Dart中的混合器:如何使用它们

Dart中的混合器:如何使用它们,dart,mixins,Dart,Mixins,所以我尝试创建一个简单的小程序,在其中我使用mixin。我想表示一个书店并拥有两个产品(书籍、书包)……但我希望抽象类up top(Com)定义可以应用于所有产品(对象)的方法,而无需更改单个类。然而,我不知道如何实现这一点。该方法可以像跟踪书店中的某本书一样简单 这是我目前的代码: abstract class Com { not sure not sure } class Product extends Object with Com { String name; double pric

所以我尝试创建一个简单的小程序,在其中我使用mixin。我想表示一个书店并拥有两个产品(书籍、书包)……但我希望抽象类up top(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');

 }

Dart mixin目前只是一包成员,您可以将其复制到另一个类定义的顶部。 它类似于实现继承(
扩展
),只是扩展了超类,但使用mixin进行了扩展。因为您只能有一个超类,所以mixin允许您使用一种不同的(而且限制更多)方式来共享实现,而不需要超类了解您的方法

您在这里描述的内容听起来像是可以使用公共超类来处理的。只需将方法放在
Product
上,让
Bag
Book
都扩展该类。如果您没有任何不需要mixin方法的
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);
}

Dart mixin目前只是一包成员,您可以将其复制到另一个类定义的顶部。 它类似于实现继承(
扩展
),只是扩展了超类,但使用mixin进行了扩展。因为您只能有一个超类,所以mixin允许您使用一种不同的(而且限制更多)方式来共享实现,而不需要超类了解您的方法

您在这里描述的内容听起来像是可以使用公共超类来处理的。只需将方法放在
Product
上,让
Bag
Book
都扩展该类。如果您没有任何不需要mixin方法的
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);
}