泛型类生成器实例
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
相关文章推荐
- ACM算法竞赛:抄课文
- 判断二叉平衡树的三种方法
- Linux性能分析的前60000毫秒
- 基础理论部分
- hdu 2689 Sort it
- ACM算法竞赛:抄课文
- ACM算法竞赛:抄课文
- codeforces 705B:Spider Man
- Cookie和Session
- 使用PowerShell发送带附件的Email
- ajax 请求数据html5版(简单 但兼容性不强)
- c++编写类String的构造函数、析构函数和赋值函数
- 图论 BFS HDU 1548
- Generating Fast, Sorted Permutation
- 验证信用卡
- 获取webdav服务器目录结构注意事项
- 真机报错:dyld`dyld_fatal_error: -> 0x120085088 <+0>: brk #0x3
- HDU 1710 Binary Tree Traversals (二叉树遍历)
- 学习技能表
- 进击Node.js基础(二)promise