美文网首页
迭代器模式

迭代器模式

作者: simplerandom | 来源:发表于2020-05-20 11:55 被阅读0次

    Iterator(迭代器接口):
    ConcreteIterator(迭代器实现类):
    Aggregate(容器接口):
    ConcreteAggregate(容器实现类):

    public interface IDieDai<T> {
        Boolean hasNext();
    
        T next();
    
    }
    
    public class DieDai<T> implements IDieDai<T> {
        ArrayList<T> list = new ArrayList<>();
    
        public DieDai(ArrayList<T> list) {
            this.list = list;
        }
    
        int size = 0;
    
        @Override
        public Boolean hasNext() {
            return size != list.size();
        }
    
        @Override
        public T next() {
            T value = null;
            if (hasNext() == true) {
                value = this.list.get(size++);
            }
            return value;
        }
    
    }
    
    
    public interface IContainer<T> {
        void add(T t);
    
        void remove(T t);
    
        IDieDai dieDai();
    }
    
    public class Container<T> implements IContainer<T> {
        ArrayList<T> list = new ArrayList<>();
    
        @Override
        public void add(T o) {
            list.add(o);
        }
    
        @Override
        public void remove(T o) {
            list.add(o);
        }
    
        @Override
        public IDieDai dieDai() {
            return new DieDai(this.list);
        }
    }
    
    

    测试

    public class Test {
        public static void main(String[] args) {
            Container<String> stringContainer = new Container<>();
            stringContainer.add("hello");
            stringContainer.add("world");
            IDieDai iDieDai = stringContainer.dieDai();
            while (iDieDai.hasNext()){
                System.out.println(iDieDai.next());
            }
        }
    }
    
    

    相关文章

      网友评论

          本文标题:迭代器模式

          本文链接:https://www.haomeiwen.com/subject/flmgohtx.html