大话设计模式_迭代器模式

以公交售票员收票为例子。

一:自己实现的迭代器

package com.wzs.design;

import java.util.ArrayList;
import java.util.List;

/**
 * 大话设计模式--page202 迭代器模式
 * 
 * @author Administrator
 * 
 */
public class IteratorPattern {
	public static void main(String[] args) {
		ConcreteAggregate a = new ConcreteAggregate();
		a.set("大鸟");
		a.set("小菜");
		a.set("行李");
		a.set("老外");
		a.set("公交内部员工");
		a.set("小偷");

		Iterator iterator = new ConcreteIterator(a);
		while (!iterator.idDone()) {
			System.out.println(iterator.currentItem() + "\t请买车票.");
			iterator.next();
		}
	}
}

/*
 * Iterator迭代器抽象类
 */
abstract class Iterator {
	// 第一个
	public abstract Object first();

	// 下一个
	public abstract Object next();

	// 时候到结尾
	public abstract boolean idDone();

	// 当前对象
	public abstract Object currentItem();
}

/*
 * 具体迭代器
 */
class ConcreteIterator extends Iterator {
	private ConcreteAggregate aggregate;
	private int current = 0;

	public ConcreteIterator(ConcreteAggregate aggregate) {
		this.aggregate = aggregate;
	}

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

	@Override
	public Object next() {
		Object ret = null;
		current++;
		if (current < aggregate.count()) {
			ret = aggregate.get(current);
		}
		return ret;
	}

	@Override
	public Object currentItem() {
		return aggregate.get(current);
	}

	@Override
	public boolean idDone() {
		return current >= aggregate.count() ? true : false;
	}

}

/*
 * Aggregate聚集抽象类
 */
abstract class Aggregate {
	public abstract Iterator createIterator();
}

/*
 * ConcreteAggregate具体聚集类
 */
class ConcreteAggregate extends Aggregate {
	private List<Object> items = new ArrayList<Object>();

	@Override
	public Iterator createIterator() {
		return new ConcreteIterator(this);
	}

	public int count() {
		return items.size();
	}

	public Object get(int index) {
		return items.get(index);
	}

	public void set(Object value) {
		items.add(value);
	}
}


二:Java中的迭代器

package com.wzs.design;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

/*
 * java迭代器
 */
public class JavaIterator {
	public static void main(String[] args) {
		List<Integer> list = new ArrayList<Integer>();
		Random random = new Random();
		for (int i = 0; i < 10; i++) {
			list.add(random.nextInt(20));
		}
		System.out.println("数组元素:" + list);
		System.out.println("迭代结果:");
		Iterator<Integer> iterator = list.iterator();
		while (iterator.hasNext()) {
			System.out.print(iterator.next() + " ");
		}
	}
}


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