码迷,mamicode.com
首页 > 其他好文 > 详细

迭代器模式

时间:2016-08-05 19:58:04      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:

定义:提供一种方法访问一个容器中的各个元素,而又不暴露该对象的内部细节

类图:
技术分享

代码:
public interface Iterator {

	public Object next();
	
	public boolean hasNext();
	
	public boolean remove();
}

public class ConcreteIterator implements Iterator{
	
	private Vector vector = new Vector();
	public int cursor = 0;
	
	public ConcreteIterator(Vector vector){
		this.vector = vector;
	}

	@Override
	public Object next() {
		Object result = null;
		if(hasNext()){
			result = this.vector.get(cursor);
		}else{
			result = null;
		}
		
		return result;
	}

	@Override
	public boolean hasNext() {
		if(cursor == vector.size()){
			return false;
		}else{
			return true;
		}
	}

	@Override
	public boolean remove() {
		vector.remove(cursor);
		return true;
	}

}

public interface Aggregate {

	public void add(Object object);
	
	public void remove(Object object);
	
	public Iterator iterator();
}

public class ConcreteAggregate implements Aggregate{
	
	private Vector vector = new Vector();

	@Override
	public void add(Object object) {
		
		vector.add(object);
	}

	@Override
	public void remove(Object object) {
		
	}

	@Override
	public Iterator iterator() {
	
		return new ConcreteIterator(vector);
	}

}



迭代器模式

标签:

原文地址:http://blog.csdn.net/renpengddxx/article/details/52131516

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!