迭代器模式

来源:互联网 发布:漫威英雄实力排名知乎 编辑:程序博客网 时间:2024/06/06 08:43

迭代模式就是提供一种遍历方式,像list、set等都实现了迭代模式。我们下面实现对String字符的遍历:

public class MyIterator {    interface iterator {        Object next();        boolean hasNext();    }    static class MyString implements iterator {        private String string;        private int cursor = 0;        public void setString(String string) {//装饰者模式            this.string = string;        }        public boolean hasNext() {            if (string == null || cursor == string.length()) {                return false;            }            return true;        }        public Character next() {            Character obj = null;            if (this.hasNext()) {                char[] dst = new char[string.length()];                string.getChars(0, string.length(), dst, 0);                obj = dst[cursor++];            }            return obj;        }    }    public static void main(String[] args) {        MyString myString = new MyString();        myString.setString("哈哈啊");        for (MyString it = myString; it.hasNext(); ) {            System.out.println(it.next());        }    }}输出:哈哈啊

其实,我们只要实现了上面的iterator接口就是迭代器模式了。它只是一种遍历方式,与怎样实现无关。

觉得容易理解的话面向对象的23种设计模式点这里