【问题标题】:Haxe: Null object pattern for iterablesHaxe:可迭代的空对象模式
【发布时间】:2016-08-11 07:43:27
【问题描述】:

我想为 Iterable 类实现 Null Object 设计模式。例如,如果我的内部数组未初始化,则包装类无论如何都会返回不会破坏主逻辑的空迭代器:

public function iterator():Iterator<T> {
  // ...of cause it doesn't work, because Iterator is typedef not class
  return mList != null ? mList.iterator() : new Iterator<T>();
}

var mList:Array<T>;

我应该使用所需类型的项目或其他实现 Iterator 接口但什么都不包含的东西来实例化静态空虚拟数组吗?或者可能有更直接的解决方案?

【问题讨论】:

    标签: object design-patterns null haxe iterable


    【解决方案1】:

    您可以通过添加某种 isEmpty 函数在对象类本身中进行正手检查:

    public function isEmpty():Bool {
      return mList == null || mList.length == 0;
    }
    

    然后像这样使用它:

    if(!iter.isEmpty()) {
      for(i in iter) {
        trace(i);
      }
    }
    

    示例:http://try.haxe.org/#8719E

    或者

    您可以为此使用虚拟迭代器:

    class NullIterator  {
        public inline function hasNext() return false;
        public inline function next() return null;
        public inline function new() {}
    }
    

    ..并像这样使用它

    public function iterator():Iterator<T> {
      return mList != null ? mList.iterator() : new NullIterator();
    }
    

    示例:http://try.haxe.org/#B2d7e

    如果您认为应该改变行为,那么您可以在 Github 上提出问题。 https://github.com/HaxeFoundation/haxe/issues

    【讨论】:

      猜你喜欢
      • 2013-03-09
      • 1970-01-01
      • 2019-06-03
      • 2021-07-03
      • 2019-10-15
      • 2012-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多