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

设计模式之迭代器模式

时间:2014-10-05 15:36:18      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   ar   java   sp   2014   c   on   

定义:提供一种方法顺序访问一个聚合对象中各个元素,而又不暴露该对象的内部表示。

结构图:

bubuko.com,布布扣

示例代码:

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);
	}
}
客户端代码如下:

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

菜鸟

阿里



设计模式之迭代器模式

标签:style   blog   http   ar   java   sp   2014   c   on   

原文地址:http://blog.csdn.net/tiandesheng111/article/details/39802777

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