使用Dart语言扩展基本List类和额外功能

时间:2013-08-27 07:12:17

标签: class inheritance dart extend

这个问题是关于Dart语言的。 我想要一个只是List但具有一些额外功能的类。

例如,我有一个名为Model的类:

class Model{
  String name;
  int type;
  Model(this.name, this.type);
}

我知道Model的类型只能有四个值:从0到3。 我想要一个方法,它可以给我一个指定类型的模型列表,例如List<Model> modelCollection.getByType(int type);。 我打算在该类中有四个“隐藏”模型列表(按类型分组)。 因此,我需要覆盖List元素的添加和删除,以使隐藏列表保持最新。

我怎样才能尽可能简单地认识到这一点?

P.S。我知道这很简单,但我对Object继承不太熟悉并且找不到合适的例子。 P.P.S.我也检查了这个,但不知道它是否过时,并没有抓住这个想法。

3 个答案:

答案 0 :(得分:7)

要创建类实现List,有以下几种方法:

import 'dart:collection';

class MyCustomList<E> extends ListBase<E> {
  final List<E> l = [];
  MyCustomList();

  void set length(int newLength) { l.length = newLength; }
  int get length => l.length;
  E operator [](int index) => l[index];
  void operator []=(int index, E value) { l[index] = value; }

  // your custom methods
}
import 'dart:collection';

class MyCustomList<E> extends Base with ListMixin<E> {
  final List<E> l = [];
  MyCustomList();

  void set length(int newLength) { l.length = newLength; }
  int get length => l.length;
  E operator [](int index) => l[index];
  void operator []=(int index, E value) { l[index] = value; }

  // your custom methods
}
import 'package:quiver/collection.dart';

class MyCustomList<E> extends DelegatingList<E> {
  final List<E> _l = [];

  List<E> get delegate => _l;

  // your custom methods
}

根据您的代码,每个选项都有其优点。如果您包装/委托现有列表,则应使用最后一个选项。否则,根据您的类型层次结构使用两个第一个选项中的一个(mixin允许扩展其他对象)。

答案 1 :(得分:2)

基本方法是使用IterableMixin扩展对象。你似乎甚至不需要覆盖“长度”getter,或者说IterableMixin已经提供的所有方法。

import 'dart:collection';    

class Model {
   String name;
   int type;

   Model(this.name, this.type) {
   }
}

class ModelCollection extends Object with IterableMixin {

   List<Model> _models;
   Iterator get iterator => _models.iterator;

   ModelCollection() {
      this._models = new List<Model>();
   }

   //get one or the first type
   Model elementByType(int type) {

     for (Model model in _models) {
       if (model.type == type) {
          return model;
       }
     }       
   }

   //get all of the same type
   List<Model> elementsByType(int type) {

      List<Model> newModel = new List<Model>();

      for (Model model in _models) {
         if (model.type == type) {
            newModel.add(model);
         }
      }
      return newModel;       
   }

   add(Model model) {
      this._models.add(model);
   }
}

请原谅我的强力静态打字。

答案 2 :(得分:1)

您可能对quiver.dart的Multimap感兴趣。它的行为类似于允许每个键有多个值的Map。

以下是github上的代码:https://github.com/google/quiver-dart/blob/master/lib/src/collection/multimap.dart#L20

它就像酒吧一样在酒吧里。我们很快就会在某个地方举办dartdocs。

相关问题