設計模式-行為篇(迭代器模式)

weixin_33831196發表於2017-02-10

迭代器模式:

又叫做遊標(Cursor)模式。
提供一種方法訪問一個容器(container)物件中的各個元素,而又不暴露該物件的內部細節。

/**
 * Created by malei on 2016/12/6.
 */
public class MyList<T> implements Collect<T>{

    private List list = new ArrayList();

    @Override
    public void add(T obj) {
        list.add(obj);
    }

    @Override
    public void remove(T obj) {
        list.remove(obj);
    }

    @Override
    public Iterator iterator() {
        return new MyIterator(list);
    }

    public static void main(String[] args){
        Collect<String> list = new MyList<>();
        list.add("小米1");
        list.add("小米2");
        list.add("小米3");

        Iterator it = list.iterator();
        while (it.hasNext()){
            Log.show((String)it.next());
        }
    }
}

/**
 * Created by malei on 2016/12/6.
 * 集合的介面規範
 */
public interface Collect<T> {
    void add(T obj);
    void remove(T obj);
    Iterator iterator();
}

/**
 * Created by malei on 2016/12/6.
 */
public class MyIterator<T> implements Iterator{

    private List<T> list = new ArrayList();
    private int cursor = 0;

    public  MyIterator(List<T> list){
        this.list = list;
    }

    @Override
    public T next() {
        T obj = null;
        if(this.hasNext()){
            obj = this.list.get(cursor++);
        }
        return obj;
    }

    @Override
    public boolean hasNext() {
        if(cursor == list.size()){
            return false;
        }
        return true;
    }
}

/**
 * Created by malei on 2016/12/6.
 * 迭代器介面
 */
public interface Iterator <T>{
    T next();
    boolean hasNext();
}

相關文章