泛型也可用于接口之中,我们可以使用泛型接口来生成工厂模式,当然在接口工厂是不需要任何参数的就会知道如何创建对象的
public interface Generator <T>{
T next();
}
public class Coffe {
private static long count=0;
private final long id=count++;
@Override
public String toString() {
return getClass().getSimpleName()+" "+id;
}
}
public class Americano extends Coffe{
}
public class Breve extends Coffe{
}
public class Cappuccino extends Coffe{
}
public class Latte extends Coffe {
}
public class Mocha extends Coffe{
}
public class CoffeeGenerator implements Generator<Coffe>{
private Class[] types={Latte.class,Mocha.class,Cappuccino.class,Breve.class,Americano.class};
private static Random random=new Random(47);
public CoffeeGenerator(){ }
@Override
public Coffe next() {
Coffe o=null;
try {
o = (Coffe) types[random.nextInt(types.length)].newInstance();
} catch (Exception e) {
System.out.println("对象创建失败");
}
return o;
}
public static void main(String[] args) {
CoffeeGenerator coffeeGenerator = new CoffeeGenerator();
for (int i = 0; i < 5; i++) {
System.out.println(coffeeGenerator.next());
}
}
}