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

    泛型相关请参考:http://www.cnblogs.com/lwbqqyumidi/p/3837629.html

    uml:

    Aggregate及其子类:

    public abstract class Aggregate<T> {
    	
    	public abstract Iterator<T> getIterator();
    	public abstract T get(int index);
    	public abstract int getLength();
    	public abstract void add(T e);
    	public abstract void remove(T e);
    
    }
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class ConcreteAggregate<T> extends Aggregate<T> {
    	
    	private List<T> list = new ArrayList<>();
    	
    	@Override
    	public int getLength(){
    		return list.size();
    	}
    	
    	@Override
    	public void add(T item) {
    		list.add(item);
    	}
    	
    	@Override
    	public void remove(T item) {
    		list.remove(item);
    	}
    	
    	@Override
    	public T get(int index){
    		return list.get(index);
    	}
    
    	@Override
    	public Iterator<T> getIterator() {
    		return new ConcreteIterator<T>(this);
    	}
    
    }
    

      

    Iterator及其子类:

    public abstract class Iterator<T> {
    	
    	public abstract boolean hasNext();
    	public abstract T next();
    }
    
    public class ConcreteIterator<T> extends Iterator<T> {
    	
    	private ConcreteAggregate<T> aggr;
    	private int current = 0;
    	
    	public ConcreteIterator(ConcreteAggregate<T> aggr) {
    		this.aggr = aggr;
    	}
    
    	@Override
    	public boolean hasNext() {
    		return current < aggr.getLength() ? true : false;
    	}
    
    	@Override
    	public T next() {
    		// TODO Auto-generated method stub
    		current++;
    		return aggr.get(current - 1);
    	}
    
    }
    

    Demo:

    public class IteratorDemo {
    	
    	public static void main(String[] args) {
    		Aggregate<Integer> aggregate = new ConcreteAggregate<>();
    		for(int i = 0; i < 10; i++){
    			aggregate.add(i);
    		}
    		Iterator<Integer> iterator = aggregate.getIterator();
    		while(iterator.hasNext()){
    			System.out.println(iterator.next());
    		}
    	}
    
    }
    

      

  • 相关阅读:
    实战DeviceIoControl 之五:列举已安装的存储设备
    在NT中直接访问物理内存
    实战DeviceIoControl 之三:制作磁盘镜像文件
    实战DeviceIoControl 之六:访问物理端口
    程序员的十层楼(转)
    Vista + VS2005 源代码绑定的问题
    敬告天下IT业主
    手动卸载windows服务
    古墓丽影9的截屏
    白领饮食十大“夺命”恶习(转)
  • 原文地址:https://www.cnblogs.com/zcy-backend/p/6719612.html
Copyright © 2011-2022 走看看