【问题标题】:Mixins in Dart: How To Use ThemDart 中的 Mixins:如何使用它们
【发布时间】:2018-09-02 00:17:54
【问题描述】:

所以我正在尝试创建一个简单的小程序来使用 mixin。我想代表一家书店并拥有两种产品(书籍、包)..但我希望顶部的抽象类(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】:

    Dart mixin 目前只是一个成员包,您可以将其复制到另一个类定义的顶部。 它类似于实现继承 (extends),不同之处在于您扩展了超类,但扩展了 with 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);
    }
    

    【讨论】:

      猜你喜欢
      • 2018-02-04
      • 2019-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-02
      相关资源
      最近更新 更多