• 设计模式迭代器模式


    定义:提供一种方法来访问一个对象中的聚合的各种元件,不暴露对象的内部表示。

    图:


    演示样例代码:

    public interface Iterator {
    
    	public Object First();
    
    	public Object Next();
    
    	public boolean isDone();
    
    	public Object currentItem();
    }
    public class ConcreteIterator implements Iterator{
    
    	private ConcreteAggregate aggregate;
    	private int current = 0;
    
    	public ConcreteIterator(ConcreteAggregate aggregate) {
    		
    		this.aggregate = aggregate;
    	}
    
    	@Override
    	public Object First() {
    		// TODO Auto-generated method stub
    		return aggregate.get(0);
    	}
    
    	@Override
    	public Object Next() {
    		// TODO Auto-generated method stubg
    		Object ret = null;
    		current ++;
    		if (current < aggregate.count()) {
    			ret = aggregate.get(current);
    		}
    		return ret;
    	}
    
    	@Override
    	public boolean isDone() {
    		// TODO Auto-generated method stub
    		return current >= aggregate.count()? true : false;
    	}
    
    	@Override
    	public Object currentItem() {
    		// TODO Auto-generated method stub
    		return aggregate.get(current);
    	}
    	
    }
    
    public abstract class Aggregate {
    
    	public abstract Iterator createIterator();
    }
    
    public class ConcreteAggregate extends Aggregate {
    
    	private List<Object> items = new ArrayList<Object>();
    
    	@Override
    	public Iterator createIterator() {
    		// TODO Auto-generated method stub
    		return new ConcreteIterator(this);
    	}
    
    	public int count() {
    		return items.size();
    	}
    
    	public Object get(int index) {
    
    		return items.get(index);
    	}
    
    	public void add(Object obj) {
    		items.add(obj);
    	}
    }
    
    client代码例如以下:

    public class Client {
    
    	public static void main(String[] args) {
    		
    		ConcreteAggregate a = new ConcreteAggregate();
    		a.add("123");
    		a.add("菜鸟");
    		a.add("阿里");
    		
    		Iterator i = new ConcreteIterator(a);
    		Object item = i.First();
    		while (!i.isDone()) {
    			System.out.println(i.currentItem());
    			i.Next();
    		}
    	}
    }
    

    执行结果:

    123

    菜鸟

    阿里



    版权声明:本文博客原创文章。博客,未经同意,不得转载。

  • 相关阅读:
    【mysql+RBAC】RBAC权限处理(转载:http://www.cnblogs.com/xiaoxi/p/5889486.html 平凡希)
    【小程序】获取微信 自带的 收货地址获取和整理
    【TP3.2】跨库操作和跨域操作
    【JS】一款好用的JS日历选择插件【bootstrap-datetimepicker.js】
    Python 读写文件中w与wt, r与rt的区别
    Python 在序列上跟踪索引和值
    SoapUI 使用变量
    python 跳过可迭代对象的开始部分
    Python 迭代器切片
    Python: 类中为什么要定义__init__()方法
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/4628353.html
Copyright © 2020-2023  润新知