java 泛型2——泛型接口
泛型也可以应用于接口,这边以生成器gennerator为例,生成器是一种专门负责创建对象的类。实际上,这就是工厂方法设计模式的一种应用。不过,当使用生成器创建新的对象时,他不需要任何参数,而工厂方法一般需要参数。也就是说,生成器无需额外信息即可创建对象。
首先生成器接口定义如下:
package com.zy.test; public interface Generator<T> { T next(); }
然后定义一些需要的类:
package com.zy.test; public class Coffee { private static long count = 0; private final long id = count++; public String toString() { return getClass().getSimpleName() + " " + id; } } class Latte extends Coffee {} class Mocha extends Coffee {} class Cappuccino extends Coffee {} class Americano extends Coffee {} class Breve extends Coffee {}
现在编写一个类实现Generator<Coffee>接口,它能够随机生成不同类型的Coffee对象:
package com.zy.test; import java.util.Iterator; import java.util.Random; public class CoffeeGenerator implements Generator<Coffee>, Iterable<Coffee> { private Class[] types = { Latte.class, Mocha.class, Cappuccino.class, Americano.class, Breve.class}; private static Random rand = new Random(47); public CoffeeGenerator() { } private int size; public CoffeeGenerator(int size) { this.size = size; } @Override public Coffee next() { try { return (Coffee)types[rand.nextInt(types.length)].newInstance(); } catch (InstantiationException | IllegalAccessException e) { e.printStackTrace(); throw new RuntimeException(e); } } class CoffeeIterator implements Iterator<Coffee> { int count = size; @Override public boolean hasNext() { return count > 0; } @Override public Coffee next() { count--; return CoffeeGenerator.this.next(); } public void remove() { throw new UnsupportedOperationException(); } } @Override public Iterator<Coffee> iterator() { return 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); } } }
输出:
Americano 0 Latte 1 Americano 2 Mocha 3 Mocha 4 Breve 5 Americano 6 Latte 7 Cappuccino 8 Cappuccino 9
上一篇:
IDEA上Java项目控制台中文乱码