生成器,是一种专门负责创建对象的类,它不同于工厂方法,它创建对象时,它不需要任何参数,这里生成器将会设计利用了泛型。
//生成器接口
public interface Generator <T>
{
T next();
}
//公共父类
public class Coffee
{
private static long counter = 0;
//标记每个子类的标识值
private final long id = counter++;
public String toString()
{
return getClass().getSimpleName() + " " + id;
}
}
//子类
public class Latte extends Coffee {}
public class Mocha extends Coffee {}
public class Cappuccino extends Coffee {}
public class Americano extends Coffee {}
public class Breve extends Coffee {}
//编一个随机生成器实现生成器和迭代器接口
public class CoffeeGenerator implements Generator<Coffee>,Iterable<Coffee>
{
//要随机生成的这些对象
@SuppressWarnings("rawtypes")
private Class[] type={Latte.class,Mocha.class,Cappuccino.class,Americano.class,Breve.class};
private static Random random=new Random(47);
//迭代次数
private int size=0;
public CoffeeGenerator(int size)
{
super();
this.size = size;
}
public CoffeeGenerator()
{
super();
}
@Override
public Iterator<Coffee> iterator()
{
return new CofferIterator();
}
//返回一个随机产生的对象
@Override
public Coffee next()
{
try
{
return (Coffee)type[random.nextInt(type.length)].newInstance();
} catch (Exception e)
{
throw new RuntimeException(e);
}
}
//内部类的迭代器
class CofferIterator implements Iterator<Coffee>
{
int count=size;
//末端哨兵
@Override
public boolean hasNext()
{
return count>0;
}
@Override
public Coffee next()
{
count--;
return CoffeeGenerator.this.next();
}
@Override
public void remove()
{
throw new UnsupportedOperationException();
}
}
public static void main(String[] args)
{
CoffeeGenerator generator=new CoffeeGenerator();
//用循环创建对象
for(int i=0;i<5;i++)
System.out.println(generator.next());
//利用迭代器创建对象
for(Coffee c:new CoffeeGenerator(5))
System.out.println(c);
}
}
运行结果:
Americano 0
Latte 1
Americano 2
Mocha 3
Mocha 4
Breve 5
Americano 6
Latte 7
Cappuccino 8
Cappuccino 9