設計模式(十三)迭代器模式

版權聲明:轉載必須註明本文轉自曉_晨的博客: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會回你們的。
覺得寫得不錯的小夥伴,歡迎轉載,但請附上原文地址,謝謝^_^!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章