您的位置:首页 > 其它

泛型类生成器实例

2016-08-10 15:33 148 查看
待创建类型

package com.test.coffee;

public class Coffee {
private static long counter=0;
private final long id=counter++;
public String toString(){
return getClass().getSimpleName()+" "+id;
}

}<pre name="code" class="html">具体类型
package com.test.coffee;

public class Latte extends Coffee{

}

package com.test.coffee;

public class Mocha extends Coffee{

}
package com.test.coffee;

public class Cappuccino extends Coffee{

}
<pre name="code" class="html">类生成器接口
public interface Generator<T> {
T next();
}
Coffee类生成器
package com.test.coffee;import java.util.Iterator;import java.util.Random;import com.test.interfac.Generator;public class CoffeeGenerator implements Generator<Coffee>,Iterable<Coffee>{private Class[] types={Latte.class,Mocha.class,Cappuccino.class};private static Random rand=new Random(47);public CoffeeGenerator(){}private int size = 0;public CoffeeGenerator(int sz){size=sz;}@Overridepublic Coffee next() {try {return (Coffee) types[rand.nextInt(types.length)].newInstance();} catch (InstantiationException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();}return null;}class CoffeeIterator implements Iterator<Coffee>{int count = size;public boolean hasNext(){return count>0;}public Coffee next(){count--;return CoffeeGenerator.this.next();}public void remove(){}}@Overridepublic Iterator<Coffee> iterator() {// TODO Auto-generated method stubreturn new CoffeeIterator();}public static void main(String[] args) {CoffeeGenerator gen = new CoffeeGenerator();for(int i=0;i<5;i++){System.out.println(gen.next());}for(Coffee c: new CoffeeGenerator(5)){System.out.println(c);}}}
Output:
Cappuccino 0Cappuccino 1Mocha 2Cappuccino 3Mocha 4Cappuccino 5Mocha 6Cappuccino 7Latte 8Mocha 9
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: