Java泛型(2):泛型接口
泛型不仅可以在类上实现,也可以在接口上实现。JDK中[Iterable<T> <-- Collection<E> <-- List<E>/Queue<E>/Set<E>]都是泛型接口。
下面是一个泛型接口的例子。这是一个一个生成器的例子。生成器用来专门创建对象。这是工厂方法设计模式的一种应用。一般来说生成器只有一个用来生成新的对象的方法。
1 public interface Generator<T> { 2 T next(); 3 boolean hasNext(); 4 }
1 public class CoffeeGenerator implements Generator<Coffee> { 2 3 private int[] numList; 4 5 private int pos; 6 7 public CoffeeGenerator(int[] numList) { 8 this.numList = numList; 9 pos = 0; 10 } 11 12 @Override 13 public Coffee next() { 14 switch (numList[pos++]) { 15 case Cappuccino.NUM: 16 return new Cappuccino(); 17 case Latte.NUM: 18 return new Latte(); 19 case Mocha.NUM: 20 return new Mocha(); 21 default: 22 return null; 23 } 24 } 25 26 @Override 27 public boolean hasNext() { 28 return numList != null && numList.length != 0 && numList.length > pos; 29 } 30 }
1 public interface Coffee { 2 int getPrice(); 3 void make(); 4 }
1 public class Cappuccino implements Coffee { 2 3 public final static int NUM = 1; 4 5 Cappuccino() { 6 make(); 7 } 8 9 @Override 10 public int getPrice() { 11 return 38; 12 } 13 14 @Override 15 public void make() { 16 System.out.println("Making " + getClass().getSimpleName() + "..."); 17 } 18 }
1 public class Latte implements Coffee { 2 3 public final static int NUM = 2; 4 5 Latte() { 6 make(); 7 } 8 9 @Override 10 public int getPrice() { 11 return 32; 12 } 13 14 @Override 15 public void make() { 16 System.out.println("Making " + getClass().getSimpleName() + "..."); 17 } 18 }
1 public class Mocha implements Coffee { 2 3 public final static int NUM = 3; 4 5 Mocha() { 6 make(); 7 } 8 9 @Override 10 public int getPrice() { 11 return 35; 12 } 13 14 @Override 15 public void make() { 16 System.out.println("Making " + getClass().getSimpleName() + "..."); 17 } 18 }
Main方法测试:
1 Generator<Coffee> coffeeGen = new CoffeeGenerator(new int[] { 1, 3, 2, 1, 1, 3 }); 2 int totalPrice = 0; 3 while (coffeeGen.hasNext()) { 4 Coffee coffee = coffeeGen.next(); 5 totalPrice += coffee.getPrice(); // Making Cappuccino/Mocha/Latte/Cappuccino/Cappuccino/Mocha... 6 } 7 System.out.println(totalPrice); // 216