package cn.bunny.pattern13;

import java.util.ArrayList;
import java.util.List;

public class Iterator {

    public static void main(String[] args) {
        ListContainer listContainer = new ListContainer();
        listContainer.add("序号1");
        listContainer.add("序号2");
        listContainer.add("序号3");
        listContainer.add("序号4");

        MyIterator iterator = listContainer.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }

    // 迭代器接口
    interface MyIterator {

        boolean hasNext();

        Object next();
    }

    // 定义容器
    interface MyContainer {
        void add(Object o);

        void remove(Object o);

        MyIterator iterator();
    }

    // 列表操作容器
    static class ListContainer implements MyContainer {
        private final List<Object> list = new ArrayList<>();

        @Override
        public void add(Object o) {
            list.add(o);
        }

        @Override
        public void remove(Object o) {
            list.remove(o);
        }

        @Override
        public MyIterator iterator() {
            return new MyIteratorImpl();
        }

        class MyIteratorImpl implements MyIterator {

            private int index = 0;

            @Override
            public boolean hasNext() {
                return index < list.size();
            }

            @Override
            public Object next() {
                Object object = list.get(index);
                index++;
                return object;
            }
        }
    }
}
