dart_in_action/29_design_pattern_iterator....

66 lines
1.4 KiB
Dart
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
迭代器模式Iterator Pattern
意图:提供一种方法顺序访问一个聚合对象中各个元素, 而又无须暴露该对象的内部表示。
主要解决:不同的方式来遍历整个整合对象。
何时使用:遍历一个聚合对象。
如何解决:把在元素之间游走的责任交给迭代器,而不是聚合对象。
*/
main(List<String> args) {
NameRepository namesRepository = new NameRepository();
for (Iterator iter = namesRepository.getIterator(); iter.hasNext();) {
String name = iter.next();
print("Name : $name");
}
}
//////////////////////////////////////////////////////////////////
///
/// 创建接口
///
abstract class Iterator {
bool hasNext();
Object next();
}
abstract class Container {
Iterator getIterator();
}
///
/// 创建实现了 Container 接口的实体类。实现了 Iterator 接口的类 NameIterator
///
class NameRepository implements Container {
List<String> names = ["Robert", "John", "Julie", "Lora"];
@override
Iterator getIterator() {
return NameIterator(names);
}
}
class NameIterator implements Iterator {
List<String> _names;
int _index = 0;
NameIterator(this._names);
@override
bool hasNext() {
if (_index < _names.length) {
return true;
}
return false;
}
@override
Object next() {
if (this.hasNext()) {
return _names[_index++];
}
return null;
}
}