设计模式(十三)迭代器模式

版权声明:转载必须注明本文转自晓_晨的博客:http://blog.csdn.net/niunai112

目录

导航

设计模式之六大设计原则
设计模式(一)单例模式
设计模式(二)工厂模式
设计模式(三)策略模式
设计模式(四)适配器模式
设计模式(五)享元模式
设计模式(六)建造者模式
设计模式(七)原型模式
设计模式(八)桥接模式
设计模式(九)外观模式
设计模式(十)组合模式
设计模式(十一)装饰器模式
设计模式(十二)代理模式
设计模式(十三)迭代器模式
设计模式(十四)观察者模式
设计模式(十五)中介者模式
设计模式(十六)命令模式
设计模式(十七)状态模式
设计模式(十八)访问者模式
设计模式(十九)责任链模式
设计模式(二十)解释器模式
设计模式(二十一)备忘录模式
设计模式(二十二)模板模式
设计模式总结篇(为什么要学习设计模式,学习设计模式的好处)

前言

迭代器模式:提供一种方法顺序的访问一个聚合对象中各个元素,而又不暴露该对象的内部表示。
一般是用来遍历容器用的,大部分情况不需要我们自己来实现,直接使用像ArrayList,HashMap里的Iterator就行了。
但LZ为了理解和学习这个模式,自己写了个demo。仿ArrayList的。

例子

首先定义Iterator的接口方法,有hashNext(是否还能取出元素),和next(取出元素并将下标移到下一个)
/***
 *
 *@Author ChenjunWang
 *@Description:
 *@Date: Created in 22:10 2018/4/4
 *@Modified By:
 *
 */
public interface Iterator<T> {
    boolean hasNext();
    T next();

}


/***
 *
 *@Author ChenjunWang
 *@Description:
 *@Date: Created in 16:07 2018/4/7
 *@Modified By:
 *
 */
public class ArrList<T> {

    Object[] list;


    int size;
    public  ArrList(){
        size = 0;
        list = new Object[10];//为了方便,我没有写拓容的代码,直接初始化为10个大小,望看官见谅哈。
    }
    public void add(T o){
        list[size++] = o;
    }

    public Iterator<T> iterator(){
        return new MyIterator();
    }

    public class MyIterator implements Iterator<T>{

        int index = 0;
        @Override
        public boolean hasNext() {
            if (index < size){
                return true;
            }
            return false;

        }

        @Override
        public T next() {

            return (T) list[index++];
        }
    }
}

/***
 *
 *@Author ChenjunWang
 *@Description:
 *@Date: Created in 23:56 2018/4/7
 *@Modified By:
 *
 */
public class Test {
    public static void main(String[] args) {
        ArrList<String> list = new ArrList<>();
        list.add("1");
        list.add("2");


        Iterator<String> iterator = list.iterator();

        System.out.println("迭代器开始");
        while (iterator.hasNext()) {
            String next = iterator.next();
            System.out.println(next);

        }
        System.out.println("迭代器结束");
    }

}
运行结果如下
-----------------------------------
迭代器开始
1
2
迭代器结束

以上便是LZ自己写的一个粗糙的ArrayList的迭代器。

总结

优点

(1)当你想遍历集合的时候,直接用迭代器迭代就行,不需要你知道细节的东西,使用简单方便。

缺点

(1)对于比较简单的遍历(像数组或者有序列表),使用迭代器方式遍历较为繁琐。
(2)增加了代码的复杂度。

Git地址

本篇实例Github地址:https://github.com/stackisok/Design-Pattern/tree/master/src/iterator

回到最上方


有什么不懂或者不对的地方,欢迎留言。
喜欢LZ文章的小伙伴们,可以关注一波,也可以留言,LZ会回你们的。
觉得写得不错的小伙伴,欢迎转载,但请附上原文地址,谢谢^_^!

猜你喜欢

转载自blog.csdn.net/niunai112/article/details/79841244
今日推荐