1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| package lianxi;
import java.util.Iterator; import java.util.Random;
public class CoffeeGenerator implements Generator<Coffee>, Iterable<Coffee>{ private Class[] types = {Latte.class, Mocha.class}; private static Random rand = new Random(47); public CoffeeGenerator() {} private int size = 0; public CoffeeGenerator(int size) { this.size = size; } public Coffee RandomNext() { try{ return (Coffee) types[rand.nextInt(types.length)].newInstance(); }catch(Exception e){ throw new RuntimeException(e); } } class CoffeeIterator implements Iterator<Coffee>{ int count = size; public boolean hasNext(){ return count > 0;} public Coffee next(){ count--; return CoffeeGenerator.this.RandomNext(); } public void remove(){ throw new UnsupportedOperationException(); } }; @Override public Iterator<Coffee> iterator(){ return new CoffeeIterator(); } public static void main(String[] arges){ CoffeeGenerator gen = new CoffeeGenerator(); for(int i = 0; i < 5; i++) System.out.println(gen.RandomNext()); System.out.println("----------------"); for(Coffee c : new CoffeeGenerator(5)) System.out.println(c); } } 输出: Mocha 0 Latte 1 Mocha 2 Latte 3 Latte 4 ---------------- Mocha 5 Latte 6 Latte 7 Mocha 8 Mocha 9
|