设计模式java——迭代器模式

迭代器模式(Iterator):提供一种方法顺序访问一个聚合对象中各个元素,而又不暴露该对象的内部表示。

迭代器模式Demo:

/**
 * 2018年4月3日下午9:48:05
 */
package com.Designpattern;

/**
 * @author xinwenfeng
 *
 */
public class TestIterator {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String[] strs = {"BM42","theone","AB"};
		MyAggregate ma = new AggregateImpl(strs);
		MyIterator mi = ma.getIterator();
		while(mi.hasnext()) {
			System.out.println(mi.next());
		}
	}

}
//抽象迭代器类
interface MyIterator{
	Object first();
	Object next();
	Object current();
	boolean hasnext();
}
//抽象聚集类
interface MyAggregate{
	MyIterator getIterator();
}
class IteratorImpl implements MyIterator{
	
	private String[] strings = null;
	
	private int index = -1;
	
	public IteratorImpl(String[] ss) {
		strings = ss;
	}

	@Override
	public Object first() {
		if(null == strings) {
			return null;
		}else if(strings.length>0){
			return strings[0];
		}else {
			return null;
		}
	}

	@Override
	public Object next() {
		index++;
		return strings[index];
	}

	@Override
	public Object current() {
		return strings[index];
	}

	@Override
	public boolean hasnext() {
		if(null == strings) {
			return false;
		}else {
			return index < strings.length-1;
		}
	}
	
}
class AggregateImpl implements MyAggregate{
	
	private String[] strs = null;
	
	public AggregateImpl(String[] strings) {
		strs = strings;
	}

	@Override
	public MyIterator getIterator() {
		return new IteratorImpl(strs);
	}
	
}

结果:


你可能感兴趣的:(设计模式Demo,java设计模式,迭代器模式)