迭代器模式 附代码

本文介绍了一种使用迭代器模式结合工厂方法实现字符串数组集合遍历的方法。通过定义自己的Iterator类并实现在集合中迭代的功能,使得集合的存储结构与遍历方式分离,遵循单一职责原则。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考这篇博客http://www.cnblogs.com/maowang1991/archive/2013/04/15/3023236.html
字符串数组集合,Collection中的iterator()方法返回自己定义的Iterator类,用到了工厂方法。迭代器模式将集合的存储和迭代分开,符合单一职责的原则。
代码如下

public class Main {
    public static void main(String[] args) {
        MyCollection myCollection = new MyCollection();
        Iterator iterator = myCollection.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
        //System.out.println(iterator.first());
        //System.out.println(iterator.next());
    }
}

interface Collection{
    Iterator iterator(); //工厂模式
    String get(int pos);
    int size();
}

interface Iterator{
    String next();
    boolean hasNext();
    String previous();
    String first();
}

class MyIterator implements Iterator{
    private Collection collection;
    private int pos = -1;

    public MyIterator(Collection collection) {
        this.collection = collection;
    }

    @Override
    public String 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;
    }

    @Override
    public String previous() {
        if (pos > 0){
            --pos;
        }
        return collection.get(pos);
    }

    @Override
    public String first() {
        pos = 0;
        return collection.get(pos);
    }
}

class MyCollection implements Collection{
    String[] string = {"A","B","C","D","E"};
    @Override
    public Iterator iterator() {
        return new MyIterator(this);
    }

    @Override
    public String get(int pos) {
        return string[pos];
    }

    @Override
    public int size() {
        return string.length;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值