Google Dart是否支持mixins?

时间:2011-10-10 09:47:28

标签: mixins dart

我已经浏览了language documentation,似乎Google Dart不支持mixins(接口中没有方法体,没有多重继承,没有类似Ruby的模块)。我对此是正确的,还是有另一种方法在Dart中具有类似mixin的功能?

3 个答案:

答案 0 :(得分:9)

我很高兴地报告答案现在是的!

mixin实际上只是子类和超类之间的增量。然后,您可以将该delta与另一个类“混合”。

例如,考虑这个抽象类:

 abstract class Persistence {  
  void save(String filename) {  
   print('saving the object as ${toJson()}');  
  }  

  void load(String filename) {  
   print('loading from $filename');  
  }  

  Object toJson();  
 } 

然后,您可以将其混合到其他类中,从而避免继承树的污染。

 abstract class Warrior extends Object with Persistence {  
  fight(Warrior other) {  
   // ...  
  }  
 }  

 class Ninja extends Warrior {  
  Map toJson() {  
   return {'throwing_stars': true};  
  }  
 }  

 class Zombie extends Warrior {  
  Map toJson() {  
   return {'eats_brains': true};  
  }  
 } 

对mixin定义的限制包括:

  • 不得声明构造函数
  • 超类是对象
  • 不包含对超级
  • 的调用

一些额外的阅读:

答案 1 :(得分:5)

答案 2 :(得分:2)

编辑:

Dart团队现在released their proposal for Mixins,原issue for Mixins was here

它还没有实现,但与此同时我发布了一个可扩展的Dart Mixins库,它包含了流行的Underscore.js功能实用程序库的端口:https://github.com/mythz/DartMixins

相关问题