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());
    		}
    	}
    
    }
    

      

  • 相关阅读:
    dubbo springcloud区别
    rpc
    centos7 安装docker
    vibox安装
    知识点
    spring cloud
    微服务设计原则
    工具类
    xss--知识点
    java基础--注解
  • 原文地址:https://www.cnblogs.com/zcy-backend/p/6719612.html
Copyright © 2011-2022 走看看