迭代器模式是为了方便遍历集合而产生, 但现在java提供的迭代器基本上已经能满足程序员的需求, 所以这就成为该模式慢慢没落的原因。 不过还是简单介绍一下吧。
我们以遍历用户列表来获取用户资料为例。
先定义用户资料类, 纯pojo
public class UserInfo {
private String userName;
private String address;
private String gender;
// gets & sets
}
然后定义User接口
public interface User {
void addUser(UserInfo userInfo);
String getUserInfo();
UserIterator iterator();
}
User实现类 - Programmer
public class Programmer implements User {
private UserInfo userInfo;
private List<User> userList = new ArrayList<User>();
private Programmer(UserInfo userInfo) {
this.userInfo = userInfo;
}
public Programmer() {
// No logic.
}
@Override
public void addUser(UserInfo userInfo) {
this.userList.add(new Programmer(userInfo));
}
@Override
public String getUserInfo() {
return "姓名 :" + this.userInfo.getUserName() + " 性别:"
+ this.userInfo.getGender() + " 住址:"
+ this.userInfo.getAddress();
}
@Override
public UserIterator iterator() {
return new ProgrammerIterator(this.userList);
}
}
再定义一个UserIterator接口, 继承Iterator接口
public interface UserIterator extends Iterator {
}
接着便是具体的ProgrammerIterator出场
public class ProgrammerIterator implements UserIterator {
private List<User> userList = new ArrayList<User>();
private int currentIndex;
public ProgrammerIterator(List<User> userList) {
this.userList = userList;
}
@Override
public boolean hasNext() {
if (this.currentIndex >= this.userList.size()
|| this.userList.get(this.currentIndex) == null)
return false;
return true;
}
@Override
public Object next() {
return this.userList.get(this.currentIndex++);
}
@Override
public void remove() {
this.userList.remove(this.currentIndex--);
}
}
好了, 来看看客户端代码:
public class Client {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
User user = new Programmer();
UserInfo zhangSan = new UserInfo();
zhangSan.setUserName("张三");
zhangSan.setGender("男");
zhangSan.setAddress("长江1号");
UserInfo liSi = new UserInfo();
liSi.setUserName("李四");
liSi.setGender("女");
liSi.setAddress("长江7号");
user.addUser(zhangSan);
user.addUser(liSi);
Iterator iter = user.iterator();
while (iter.hasNext()) {
User programmer = (User) iter.next();
System.out.println(programmer.getUserInfo());
}
}
}
执行接结果:
引用
姓名 :张三 性别:男 住址:长江1号
姓名 :李四 性别:女 住址:长江7号