• 23种设计模式之迭代器模式


    迭代器模式(Iterator):提供一种方法顺序访问一个聚合对象中各个元素,而又不暴露该对象的内部表示。

    package designMode.iterator;
    
    interface Aggregate {
        
        Iterator createIterator();
    }
    package designMode.iterator;
    
    interface Iterator {
        
        Object first();
        
        Object next();
        
        boolean isDone();
        
        Object currentItem();
    }
    package designMode.iterator;
    
    import java.util.ArrayList;
    import java.util.List;
    
    class ConcreteAggregate implements Aggregate{
        
        private List<Object> items = new ArrayList<Object>();
    
        @Override
        public Iterator createIterator() {
            return new ConcreteIterator(this);
        }
        
        public int count(){
            return items.size();
        }
        
        public Object getCurrent(int index){
            return items.get(index);
        }
        public void setCurrent(int index,Object value){
            items.add(index, value);
        }
    }
    package designMode.iterator;
    
    class ConcreteIterator implements Iterator{
        
        private ConcreteAggregate aggregate;
        private int current;
        
        public  ConcreteIterator(ConcreteAggregate aggregate) {
            this.aggregate = aggregate;
        }
    
        @Override
        public Object first() {
            return aggregate.getCurrent(0);
        }
    
        @Override
        public Object next() {
            Object ret = null;
            current++;
            if(current<aggregate.count())
                ret = aggregate.getCurrent(current);
            return ret;
        }
    
        @Override
        public boolean isDone() {
            return current>=aggregate.count()?true:false;
        }
    
        @Override
        public Object currentItem() {
            return aggregate.getCurrent(current);
        }
    
    }
    package designMode.iterator;
    
    class Test {
        public static void main(String[] args) {
            ConcreteAggregate a = new ConcreteAggregate();
            a.setCurrent(0, "张三");
            a.setCurrent(1, "李四");
            a.setCurrent(2, "王五");
            a.setCurrent(3, "马六");
            a.setCurrent(4, "田七");
            a.setCurrent(5, "茅八");
            Iterator iter = new ConcreteIterator(a);
            Object firstItem = iter.first();
            System.out.println("第一个是:"+firstItem);
            while(!iter.isDone()){
                System.out.println(iter.currentItem()+"已通过!");
                iter.next();
            }
        }
    }
  • 相关阅读:
    Fluent动网格【8】:网格节点运动案例
    Fluent动网格【7】:网格节点运动
    Fluent动网格【6】:部件变形案例
    Fluent动网格【5】:部件变形
    Fluent动网格【4】:DEFINE_CG_MOTION宏实例
    Fluent动网格【3】:DEFINE_CG_MOTION宏
    Fluent动网格【1】:概述
    Fluent动网格【2】:Profile文件
    JavaScript系列--浅析原型链与继承
    简单说说JavaScript的Generator 实现(ES6)
  • 原文地址:https://www.cnblogs.com/lxcmyf/p/7418002.html
Copyright © 2020-2023  润新知