Haxe:可迭代对象的空对象模式

Haxe: Null object pattern for iterables

我想为 Iterable class 实现空对象设计模式。例如,如果我的内部数组未初始化,包装器 class 无论如何 returns 不破坏主要逻辑的空迭代器:

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 接口但不包含任何内容的东西来实例化静态空虚拟数组吗?或者可能有更直接的解决方案?

您可以在对象 class 本身中进行正手检查,方法是添加某种 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