日期:2014-05-20 浏览次数:20981 次
public class RandomShapeIterable implements Iterator<Shape> {
	private Random rand = new Random(27);
	private final int generateShapeNum;
	public RandomShapeIterable( int generateShapeNum ) {
		this.generateShapeNum = generateShapeNum;
	}
	
	public Iterator<Shape> iterator() {
		return new Iterator<Shape>() {
			private int num = 0;
			public boolean hasNext() {
				return num < generateShapeNum;
			}
			public Shape next() {
				num++;
				switch(rand.nextInt(3)) {
				default:
				case 0: return new Circle();
				case 1: return new Square();
				case 2: return new Triangle();
				}
			}
			public void remove() {
				throw new UnsupportedOperationException();
			}
		};
	}
	public static void main(String[] args) {
		for (Shape s : new RandomShapeIterable(10)) {
			s.draw();
			s.erase();
		}
	}
}

class RandomShapeGenerator implements Iterable<Shape> {
	private Random rand = new Random(47);
	private final int quantity;
	RandomShapeGenerator(int quantity) {
		this.quantity = quantity;
	}
	public Iterator<Shape> iterator() {
		return new Iterator<Shape>() {
			private int count;
			public boolean hasNext() {
				return count < quantity;
			}
			public Shape next() {
				++count;
				return nextShape();
			}
			public void remove() { // Not implemented
				throw new UnsupportedOperationException();
			}
		};
	}
	private Shape nextShape() {
		switch (rand.nextInt(3)) {
		default:
		case 0:
			return new Circle();
		case 1:
			return new Square();
		case 2:
			return new Triangle();
		}
	}
}
public class E31_IterableRandomShapeGenerator {
	public static void main(String[] args) {
		RandomShapeGenerator rsg = new RandomShapeGenerator(10);
		for (Shape shape : rsg)
			System.out.println(shape.getClass().getSimpleName());
	}
}