public abstract class Aggregate
{
public abstract Iterator createIterator();
}
public interface Iterator
{
void first();
void next();
boolean isDone();
Object currentItem();
}
public class ConcreteAggregate extends Aggregate
{
private Object[] objs={"Monk Tang","Monkey","Pigsy","Sandy","Horse"};
public Iterator createIterator()
{
return new ConcreteIterator();
}
private class ConcreteIterator implements Iterator
{
private int currentIndex=0;
public void first()
{
currentIndex=0;
}
public void next()
{
if(currentIndex<objs.length)
{
currentIndex++;
}
}
public boolean isDone()
{
return (currentIndex>=objs.length);
}
public Object currentItem()
{
return objs[currentIndex];
}
}
}
public class Client
{
private Iterator it;
private Aggregate agg=new ConcreteAggregate()
public void operation()
{
it=agg.createIterator();
while(!it.isDone())
{
System.out.println(it.currentItem().toString());
it.next();
}
}
public void static main(String[] args)
{
Client client=new Client();
client.operation();
}
}
1.白箱聚集与外禀迭代子
public abstract class Aggregate
{
public Iterator createIterator()
{
return null;
}
}
public interface Iterator
{
void first();
void next();
boolean isDone();
Object currentItem();
}
public class ConcreteAggregate extends Aggregate
{
private Object[] objs={"Monk Tang","Monkey","Pigsy","Sandy","Horse"};
public Iterator createIterator()
{
return new ConcreteIterator(this);
}
public Object getElement(int index)
{
if(index<objs.length)
{
return objs[index];
} else {
return null;
}
}
public int size()
{
return objs.length;
}
}
public class ConcreteIterator implements Iterator
{
private ConcreteAggregate agg;
private int index=0;
private int size=0;
public ConcreteIterator(ConcreteAggregate agg)
{
this.agg=agg;
size=agg.size();
index=0;
}
public void first()
{
index=0;
}
public void next()
{
if(index<size)
{
index++;
}
}
public boolean isDone()
{
return (index>=size);
}
public Object currentItem()
{
return agg.getElement(index);
}
}
2.黑箱聚集与内禀迭代子
发表于 @ 2007年10月08日 12:43:00|评论(loading...)|编辑