泛型也可用于接口之中,我们可以使用泛型接口来生成工厂模式,当然在接口工厂是不需要任何参数的就会知道如何创建对象的

    1. public interface Generator <T>{
    2. T next();
    3. }
    4. public class Coffe {
    5. private static long count=0;
    6. private final long id=count++;
    7. @Override
    8. public String toString() {
    9. return getClass().getSimpleName()+" "+id;
    10. }
    11. }
    12. public class Americano extends Coffe{
    13. }
    14. public class Breve extends Coffe{
    15. }
    16. public class Cappuccino extends Coffe{
    17. }
    18. public class Latte extends Coffe {
    19. }
    20. public class Mocha extends Coffe{
    21. }
    22. public class CoffeeGenerator implements Generator<Coffe>{
    23. private Class[] types={Latte.class,Mocha.class,Cappuccino.class,Breve.class,Americano.class};
    24. private static Random random=new Random(47);
    25. public CoffeeGenerator(){ }
    26. @Override
    27. public Coffe next() {
    28. Coffe o=null;
    29. try {
    30. o = (Coffe) types[random.nextInt(types.length)].newInstance();
    31. } catch (Exception e) {
    32. System.out.println("对象创建失败");
    33. }
    34. return o;
    35. }
    36. public static void main(String[] args) {
    37. CoffeeGenerator coffeeGenerator = new CoffeeGenerator();
    38. for (int i = 0; i < 5; i++) {
    39. System.out.println(coffeeGenerator.next());
    40. }
    41. }
    42. }