Dart中的Mixins:如何使用它们

问题描述 投票:0回答:1

所以我正在尝试创建一个简单的小程序,我使用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');

 }
dart mixins
1个回答
1
投票

Dart mixin目前只是一大堆成员,您可以将其复制到另一个类定义的顶部。它类似于实现继承(extends),除了你扩展超类,但扩展与mixin。由于您只能拥有一个超类,因此mixins允许您使用不同(并且更受限制)的方式来共享不需要超类了解您的方法的实现。

你在这里描述的内容听起来像是可以使用一个共同的超类来处理的东西。只需将方法放在Product上,让BagBook扩展该类。如果你没有任何不需要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);
}
© www.soinside.com 2019 - 2024. All rights reserved.