Design Pattern 简明教程
Design Patterns - Iterator Pattern
迭代器模式是 Java 和 .Net 编程环境中非常常见的设计模式。此模式用于获取一种方法,在无需了解其底层表示的情况下,以顺序方式访问集合对象的元素。
Iterator pattern is very commonly used design pattern in Java and .Net programming environment. This pattern is used to get a way to access the elements of a collection object in sequential manner without any need to know its underlying representation.
迭代器模式属于行为模式类别。
Iterator pattern falls under behavioral pattern category.
Implementation
我们将创建一个描述导航方法的 Iterator 接口,以及一个返回迭代器的 Container 接口。实现 Container 接口的具体类将负责实现 Iterator 接口并使用它
We’re going to create a Iterator interface which narrates navigation method and a Container interface which retruns the iterator . Concrete classes implementing the Container interface will be responsible to implement Iterator interface and use it
我们的演示类 IteratorPatternDemo 将使用 NamesRepository(一个具体类实现)来打印存储为 NamesRepository 中集合的名称。
IteratorPatternDemo, our demo class will use NamesRepository, a concrete class implementation to print a Names stored as a collection in NamesRepository.
Step 1
创建接口。
Create interfaces.
Iterator.java
public interface Iterator {
public boolean hasNext();
public Object next();
}
Container.java
public interface Container {
public Iterator getIterator();
}
Step 2
创建实现 Container 接口的具体类。此类具有实现 Iterator 接口的内部类 NameIterator。
Create concrete class implementing the Container interface. This class has inner class NameIterator implementing the Iterator interface.
NameRepository.java
public class NameRepository implements Container {
public String names[] = {"Robert" , "John" ,"Julie" , "Lora"};
@Override
public Iterator getIterator() {
return new NameIterator();
}
private class NameIterator implements Iterator {
int index;
@Override
public boolean hasNext() {
if(index < names.length){
return true;
}
return false;
}
@Override
public Object next() {
if(this.hasNext()){
return names[index++];
}
return null;
}
}
}
Step 3
使用 NameRepository 获取迭代器并打印名称。
Use the NameRepository to get iterator and print names.
IteratorPatternDemo.java
public class IteratorPatternDemo {
public static void main(String[] args) {
NameRepository namesRepository = new NameRepository();
for(Iterator iter = namesRepository.getIterator(); iter.hasNext();){
String name = (String)iter.next();
System.out.println("Name : " + name);
}
}
}