15.3 泛型接口
泛型也可以應用於接口。例如生成器(generator),這是一種專門負責創建對象的類。實際上,這是工廠方法設計模式的一種應用。不過,當使用生成器創建新的對象時,它不需要任何參數,而工廠方法一般需要參數。也鼓是說,生成器無需額外的信息就知道如何創建新對象。
一般而言,一個生成器只定義一個方法,該方法用以產生新的對象.在這裏,就是next方法。
// A generic interface.
public interface Generator<T> { T next(); }
方法next()的返回類型是參數化的T。正如你所見到的,接口使用泛型與類使用泛型沒什麼區別。
爲了演示如何實現Generator接口,我們還需要一些別的類。例如,Coffee類層次結構如下:
public class Coffee {
private static long counter = 0;
private final long id = counter++;
public String toString() {
return getClass().getSimpleName() + " " + id;
}
}
public class Latte extends Coffee {} // 拿鐵
public class Mocha extends Coffee {} // 摩卡
public class Cappuccino extends Coffee {} // 卡布奇諾
public class Americano extends Coffee {} // 美式咖啡
public class Breve extends Coffee {}
現在,我們可以編寫一個類,實現Generator<Coffee>
接口,它能夠隨機生成不同類型的Coffee對象。
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() {}
// For iteration:
private int size = 0;
public CoffeeGenerator(int sz) { size = sz; }
public Coffee next() {
try {
return (Coffee)
types[rand.nextInt(types.length)].newInstance();
// Report programmer errors at run time:
} catch(Exception e) {
throw new RuntimeException(e);
}
}
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() { // Not implemented
throw new UnsupportedOperationException();
}
};
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);
}
} /* Output:
Americano 0
Latte 1
Americano 2
Mocha 3
Mocha 4
Breve 5
Americano 6
Latte 7
Cappuccino 8
Cappuccino 9
*///:~
參數化的Generator接口確保next()的返回值是參數的類型。CofeeGenerator同時還實現了Iterable接口,所以它可以在循環語句中使用。不過,它還需要一個“末端哨兵”來判斷何時停止,這正是第二個構造器的功能。
下面的類是Generetore<T>
接口的另一個實現,它負責生成Fibonacci(斐波那契)數列:
public class Fibonacci implements Generator<Integer> {
private int count = 0;
public Integer next() { return fib(count++); }
private int fib(int n) {
if(n < 2) return 1;
return fib(n-2) + fib(n-1);
}
public static void main(String[] args) {
Fibonacci gen = new Fibonacci();
for(int i = 0; i < 18; i++)
System.out.print(gen.next() + " ");
}
}
/* Output:
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584
*///:~
雖然我們在Fibonacci類的裏裏外外使用的都是int類型,但是其類型參數卻是Integer,這個例子引出了Java泛型的一個侷限性:基本類型無法作爲類型參數。不過,Java 5具備了自動打包和自動拆包的功能,可以很方便地在基本類型和其相應的包裝器類型之間進行轉換。通過這個例子中Fibonacci類對int的使用,我們已經看到了這種效果。
如果還想更進一步,編寫一個實現了Iterable的Fibonacci生成器。我們的一個選擇是重寫這個類,令其實現Iterable接口。不過,你並不是總能擁有源代碼的控制權,井且,除非必須這麼做,否則,我們也不願意重寫一個類。而且我們還有另一種選擇,就是創建個過配器(adapter)來實現所需的接口,我們在前面介紹過這個設計模式。
有多種方法可以實現適配器。例如,可以通過繼承來創建適配器類:
public class IterableFibonacci extends Fibonacci implements Iterable<Integer> {
private int n;
public IterableFibonacci(int count) { n = count; }
public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
public boolean hasNext() { return n > 0; }
public Integer next() {
n--;
return IterableFibonacci.this.next();
}
public void remove() { // Not implemented
throw new UnsupportedOperationException();
}
};
}
public static void main(String[] args) {
for(int i : new IterableFibonacci(18))
System.out.print(i + " ");
}
}
/* Output:
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584
*///:~
如果要在循環語句中使用IterableFibonacci,必須向IterableFibonacci的構造器提供一個邊界值,然後hasNext()方法才能知道何時應該返回false。