行为型模式-----迭代器模式(Iterator)

1、迭代器模式

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

             一是需要遍历的对象,即聚集对象;二是迭代器对象,用于对聚集对象进行遍历访问;

   

      实例一

   

// 定义集合接口
public interface Collection {

	public Iterator iterator();

	public int size();

	public Object get(int index);
}

// 定义迭代器接口
public interface Iterator {

	// 前移
	public Object pre();

	// 后移
	public Object next();

	public boolean hasNext();

	public Object first();
}

public class MyCollection implements Collection {

	private String[] context = { "1", "2", "3", "4" };

	@Override
	public Iterator iterator() {
		return new MyIterator(this);
	}

	@Override
	public int size() {
		return this.context.length;
	}

	@Override
	public Object get(final int index) {
		if (index < this.context.length) {
			return this.context[index];
		}
		return null;
	}
}

public class MyIterator implements Iterator {

	private Collection cols;
	// 初始化集合下标位置为0
	private int position = -1;

	public MyIterator(final Collection col) {
		this.cols = col;
	}

	@Override
	public Object pre() {
		if (this.position > 0) {
			this.position--;
			return this.cols.get(this.position);
		}
		return null;
	}

	@Override
	public Object next() {
		if (this.position < this.cols.size()) {
			this.position++;
			return this.cols.get(this.position);
		}
		return null;
	}

	@Override
	public boolean hasNext() {
		if (this.position < (this.cols.size() - 1)) {
			return true;
		}
		return false;
	}

	@Override
	public Object first() {
		return this.cols.get(0);
	}
}


     模拟调用:

	public static void main(final String[] args) {
		final Collection cols = new MyCollection();
		final Iterator ite = cols.iterator();
		while (ite.hasNext()) {
			final Object obj = ite.next();
			System.out.println("~~~~  : " + obj);
		}
	}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值