软件设计——迭代器模式之遍历学生信息
某班共44名同学,每名同学都有姓名,学号和年龄等属性,使用JAVA内置迭代器实现对同学信息的遍历,要求按照学号从小到大和从大到小两种次序输出学生信息。
代码:
Iterator.java
package test;
interface Iterator {
public Object next();
public boolean hasNext();
public boolean isFirst();
public Object previous();
public void setCursor(int i);
}
ConcreteAggregate.java
package test;
import java.util.ArrayList;
import java.util.List;
class ConcreteAggregate implements Aggregate {
private List list = new ArrayList();
public void add(Object obj) {
list.add(obj);
}
public Iterator iterator() {
return new ConcreteIterator(list);
}
public void remove(Object obj) {
list.remove(obj);
}
}
ConcreteIterator.java
package test;
import java.util.ArrayList;
import java.util.List;
public class ConcreteIterator implements Iterator{
private List list = new ArrayList();
private int cursor =0;
public ConcreteIterator(List list){
this.list = list;
}
public boolean hasNext() {
if(cursor==list.size()){
return false;
}
return true;
}
public boolean isFirst() {
if(cursor==0) {
return false;
}
return true;
}
public Object next() {
Object obj = null;
if(this.hasNext()){
obj = this.list.get(cursor++);
}
return obj;
}
public void setCursor(int i) {
cursor=i;
}
public Object previous() {
Object obj=null;
if(this.isFirst()) {
obj=this.list.get(--cursor);
}
return obj;
}
}
Aggregate.java
package test;
interface Aggregate {
public void add(Object obj);
public void remove(Object obj);
public Iterator iterator();
}
Client.java
package test;
public class Client {
public static void main(String[] args){
Aggregate ag = new ConcreteAggregate();
System.out.println("信1305班学生:");
for(int i=1;i<=44;i++) {
int m=20130000+i;
String s=Integer.toString(m);
ag.add(s+" 同学"+i);
m=0;
s=null;
}
Iterator it = ag.iterator();
System.out.println("***************************");
System.out.println("* 按学号从小到大输出 *");
System.out.println("***************************");
while(it.hasNext()){
String str = (String)it.next();
System.out.println(str);
}
System.out.println("***************************");
System.out.println("* 按学号从大到小输出 *");
System.out.println("***************************");
it.setCursor(44);
while(it.isFirst()){
String str = (String)it.previous();
System.out.println(str);
}
}
}