迭代模式

迭代模式:

          此模式的思想是有一个数据集合,我们写出一个算法集合,使用算法集合内的各个算法,来迭代数据集合,获得一些数据。

          最常见的就是  List 、Set 等我们常常使用的集合,采用迭代器(Iterator)进行获取集合内的元素。

 

以下模仿写了一个实现

package com.mkf.pattern;

public interface Iterator {
	public Object previous();

	public boolean hasPrevious();

	public Object next();

	public boolean hsNext();

	public Object first();

	public boolean isFirst();

	public Object last();

	public boolean isLast();
}

package com.mkf.pattern;

public interface Collection {
	public Iterator getIterator();

	public Object get(int i);

	public int size();
}

package com.mkf.pattern.impl;

import com.mkf.pattern.Collection;
import com.mkf.pattern.Iterator;

public class MyIterator implements Iterator {
	private Collection collection;
	private int pos = -1;

	public MyIterator(Collection collection) {
		this.collection = collection;
	}

	@Override
	public Object first() {
		pos = 0;
		return collection.get(pos);
	}

	@Override
	public boolean isFirst() {
		if (pos == 0) {
			return true;
		}
		return false;
	}

	@Override
	public Object last() {
		pos = collection.size() - 1;
		return collection.get(pos);
	}

	@Override
	public boolean isLast() {
		if (pos == collection.size() - 1) {
			return true;
		}
		return false;
	}

	@Override
	public Object next() {
		if (pos < collection.size() - 1) {
			pos++;
		}
		return collection.get(pos);
	}

	@Override
	public boolean hsNext() {
		if (pos < collection.size() - 1) {
			return true;
		}
		return false;
	}

	@Override
	public boolean hasPrevious() {
		if (pos > 0) {
			return true;
		}
		return false;
	}

	@Override
	public Object previous() {
		if (pos > 0) {
			pos--;
		}
		return collection.get(pos);
	}

}

package com.mkf.pattern.impl;

import com.mkf.pattern.Collection;
import com.mkf.pattern.Iterator;

public class MyCollection implements Collection {
	public String[] str = { "A", "B", "C", "D", "E", "F", "G" };

	@Override
	public Object get(int i) {
		return str[i];
	}

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

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

}

package com.mkf;

import com.mkf.pattern.Collection;
import com.mkf.pattern.Iterator;
import com.mkf.pattern.impl.MyCollection;

public class TestIterator {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Collection collection = new MyCollection();
		Iterator iterator = collection.getIterator();
		while(iterator.hsNext()){
			System.out.print(iterator.next());
			System.out.print("\t");
		}
	}

}

 运行结果为:

A B C D E F G 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值