设计模式之 迭代器模式

迭代器模式提供了顺序访问集合对象中的各种元素,而不暴露该对象的内部结构的方法。

 

image

(1)定义集合

public interface Collection{
    public Iterator iterator();
    public Object get(int i);
    public boolean add(Object object);
    public int size();
}

public class ListCollection implements Collection{
    public List list = new ArrayList();
    @Override
    public Iterator iterator(){
        return new ConcreteIterator(this);
    }
    @Override
    public Object get(int i){
        return list.get(i);
    }
    @Override
    public boolean add(Object object){
        list.add(object);
        return true;
    }
    @Override
    public int size(){
        return list.size();
    }
}

(2)定义迭代器

public interface Iterator{
    public Object prev();
    public Object next();
    public boolean hasNext();
}

public class ConcreIterator implements Iterator{
    private Collection collection;
    private int pos = -1;
    public ConcreIterator(Collection collection){
        this.collection = collection;
    }
    @Override
    public Object prev(){
        if(pos>0){
            pos--;
        }
        return collection.get(pos);
    }
    @Override
    public Object next(){
        if(pos<collection.size()-1){
            pos++;
        }
        return collection.get(pos);
    }
    @Override
    public boolean hasNext(){
        if(pos<collection.size()-1){
            return true;
        }else {
            return false;
        }
    }
}

(3)使用迭代器模式

public static void main(String[] args){
    Collection collection = new ListCollection();
    collection.add("obj1");
    Iterator it = collection.iterator();
    while (it.hasNext()){
        logger.info(it.next());
    }
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


posted @ 2021-09-07 14:18  yeren2046  阅读(44)  评论(0编辑  收藏  举报