Problem:
A team has one or multiple members, now print the member information one by one.
Solution:
iterator pattern.
1) define an iterator interface.
====================== MyIterator.java ==================
package test.pattern.iterator;
/**
* This is the customized iterator interface.
*
*/
public interface MyIterator {
public boolean hasNext();
public Object next();
}
2) define aggregate interface
====================== Aggregate.java ==================
package test.pattern.iterator;
public interface Aggregate {
MyIterator iterator();
}
3) member class to encapsulate member's information
====================== Member.java =====================
package test.pattern.iterator;
public class Member {
private String name;
private int age;
// getter and setter methods
}
4) team class to implement Aggregate class
==================== Team.java =======================
package test.pattern.iterator;
public class Team implements Aggregate {
private Member[] members;
private int last;
public Team(int maxSize) {
members = new Member[maxSize];
this.last = 0;
}
public void addMember(Member member){
this.members[last]=member;
last++;
}
public int getLength() {
return members.length;
}
public Member getMemberAt(int index) {
return members[index];
}
public MyIterator iterator() {
return new TeamIterator(this);
}
}
5) TeamIterator class to implement MyIterator interface
=================== TeamIterator.java ================
package test.pattern.iterator;
public class TeamIterator implements MyIterator {
private Team team;
private int index;
public TeamIterator(Team team) {
this.team = team;
this.index = 0;
}
public boolean hasNext() {
if (index >= 0 && index < team.getLength())
return true;
return false;
}
public Object next() {
Member member = team.getMemberAt(index);
index++;
return member;
}
}
6) test class
==================== Client.java ===================
package test.pattern.iterator;
public class Client {
public static void main(String[] args) {
Team team = new Team(5);
team.addMember(new Member("member A", 10));
team.addMember(new Member("member B", 11));
team.addMember(new Member("member C", 12));
team.addMember(new Member("member D", 13));
team.addMember(new Member("member E", 15));
MyIterator it = team.iterator();
while (it.hasNext()) {
Member mem = (Member) it.next();
System.out.println(mem.getName() + "'s age is " + mem.getAge());
}
}
}
This is the output:
member A's age is 10
member B's age is 11
member C's age is 12
member D's age is 13
member E's age is 15
------------
After jdk1.5, for-loop is another solution.
No comments:
Post a Comment