zoukankan      html  css  js  c++  java
  • 设计模式之 迭代器模式

    迭代器模式提供了顺序访问集合对象中的各种元素,而不暴露该对象的内部结构的方法。

    image

    (1)定义集合

    public interface Collection{
        public Iterator iterator();
        public Object get(int i);
        public boolean add(Object object);
        public int size();
    }
    
    public class ListCollection implements Collection{
        public List list = new ArrayList();
        @Override
        public Iterator iterator(){
            return new ConcreteIterator(this);
        }
        @Override
        public Object get(int i){
            return list.get(i);
        }
        @Override
        public boolean add(Object object){
            list.add(object);
            return true;
        }
        @Override
        public int size(){
            return list.size();
        }
    }

    (2)定义迭代器

    public interface Iterator{
        public Object prev();
        public Object next();
        public boolean hasNext();
    }
    
    public class ConcreIterator implements Iterator{
        private Collection collection;
        private int pos = -1;
        public ConcreIterator(Collection collection){
            this.collection = collection;
        }
        @Override
        public Object prev(){
            if(pos>0){
                pos--;
            }
            return collection.get(pos);
        }
        @Override
        public Object 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;
            }
        }
    }

    (3)使用迭代器模式

    public static void main(String[] args){
        Collection collection = new ListCollection();
        collection.add("obj1");
        Iterator it = collection.iterator();
        while (it.hasNext()){
            logger.info(it.next());
        }
    }

  • 相关阅读:
    Linux基本命令(一)
    Linux基本命令(一)
    前端js实现打印excel表格
    前端js实现打印excel表格
    前端js实现打印excel表格
    前端js实现打印(导出)excel表格
    前端js实现打印(导出)excel表格
    混合开发中拍照和打电话功能的代码
    混合开发中拍照和打电话功能的代码
    操作系统的发展史(科普章节)
  • 原文地址:https://www.cnblogs.com/betterwgo/p/15238010.html
Copyright © 2011-2022 走看看