利用泛型接口构造生成器(generator)
public interface Generator<T> { T next(); //接口中的默认类型都是 public abstract. }
public class Pet { private static long count = 0; private final long id = ++ count; public String toString() { return this.getClass().getSimpleName() + id; } } class Dog extends Pet {}; class Cat extends Pet {}; class TomCat extends Cat {};
package com.liusheng.generator; import java.util.Iterator; import java.util.Random; public class PetGenerator implements Generator<Pet>,Iterable<Pet>{ @SuppressWarnings("unchecked") private Class[] pets = {Dog.class,Cat.class,TomCat.class}; private Random r = new Random(213); public int size = 0; public PetGenerator() { } public PetGenerator(int size) { this.size = size; } @Override public Pet next() { try { return (Pet)pets[r.nextInt(pets.length)].newInstance(); } catch(Exception e) { throw new RuntimeException(e);// } } class PetIterator implements Iterator<Pet> { int count = size; public boolean hasNext() { return count > 0; } @Override public Pet next() { count --; return PetGenerator.this.next(); } @Override public void remove() { throw new RuntimeException(); } } @Override public Iterator<Pet> iterator() { return new PetIterator(); } }
package com.liusheng.generator; public class TestGenerator { public static void main(String[] args) { PetGenerator pg = new PetGenerator(5); for(Pet p : pg) { System.out.print(p + " , "); } } } //输出 //Dog1 , Dog2 , TomCat3 , Cat4 , Dog5 ,