迭代器模式Iterator
/**
* 自定义迭代器接口
* @author 小帆敲代码
*
*/
public interface MyIterator {
void first();//游标置于第一个
void last();//游标置于最后一个
boolean isfirst();
boolean isLast();
void next();//游标后移一个
boolean hasNext();//是否有下一个
Object getCurrentObj();//获得当前对象
}
/**
* 具体聚合类
* @author 51104
*
*/
public class ConcreteAggregation {
private List<Object> list=new ArrayList<Object>();
* 具体聚合类
* @author 51104
*
*/
public class ConcreteAggregation {
private List<Object> list=new ArrayList<Object>();
public List<Object> getList() {
return list;
}
return list;
}
public void setList(List<Object> list) {
this.list = list;
}
public void addObj(Object obj) {
list.add(obj);
}
public void removeObj(Object obj) {
list.remove(obj);
}
public MyIterator getMyIterator() {
return new ConcreteIterator();
}
//内部类可以使用外部属性
private class ConcreteIterator implements MyIterator{
private int cursor;
@Override
public void first() {
cursor=0;
}
this.list = list;
}
public void addObj(Object obj) {
list.add(obj);
}
public void removeObj(Object obj) {
list.remove(obj);
}
public MyIterator getMyIterator() {
return new ConcreteIterator();
}
//内部类可以使用外部属性
private class ConcreteIterator implements MyIterator{
private int cursor;
@Override
public void first() {
cursor=0;
}
@Override
public void last() {
cursor=list.size()-1;
}
public void last() {
cursor=list.size()-1;
}
@Override
public boolean isfirst() {
return cursor==0?true:false;
}
public boolean isfirst() {
return cursor==0?true:false;
}
@Override
public boolean isLast() {
return cursor==(list.size()-1)?true:false;
}
public boolean isLast() {
return cursor==(list.size()-1)?true:false;
}
@Override
public void next() {
if(cursor<list.size()) {
cursor+=1;
}
}
public void next() {
if(cursor<list.size()) {
cursor+=1;
}
}
@Override
public boolean hasNext() {
if(cursor==list.size())
return false;
return true;
}
public boolean hasNext() {
if(cursor==list.size())
return false;
return true;
}
@Override
public Object getCurrentObj() {
return list.get(cursor);
}
}
}
public Object getCurrentObj() {
return list.get(cursor);
}
}
}
public class Client {
public static void main(String[] args) {
ConcreteAggregation ca=new ConcreteAggregation();
ca.addObj("aa");
ca.addObj("bb");
ca.addObj("cc");
MyIterator mi=ca.getMyIterator();
while(mi.hasNext()) {
System.out.println(mi.getCurrentObj());
mi.next();
}
}
}
public static void main(String[] args) {
ConcreteAggregation ca=new ConcreteAggregation();
ca.addObj("aa");
ca.addObj("bb");
ca.addObj("cc");
MyIterator mi=ca.getMyIterator();
while(mi.hasNext()) {
System.out.println(mi.getCurrentObj());
mi.next();
}
}
}