汎用ディスカッション-----汎用インタフェース
汎用型は、クリエイティブオブジェクトを専門とするクラスであるジェネレータなどのインタフェースにも使用できます.実際には工場方法設計モデルの応用である.異なるのは、パラメータが必要ないことです.
一般的に、ジェネレータは新しいオブジェクトを生成するためのメソッドのみを定義します.
例:
補助クラス:
異なるタイプのOffeeオブジェクトをランダムに生成できるGeneratorインタフェースを実装
パラメトリックGeneratorインタフェースはnext()メソッドの戻り値がパラメータのタイプであることを確認します.
一般的に、ジェネレータは新しいオブジェクトを生成するためのメソッドのみを定義します.
例:
public interface Generator<T> { T next(); }
補助クラス:
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 Americano extends Coffee {}
異なるタイプのOffeeオブジェクトをランダムに生成できるGenerator
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);
}
}
パラメトリックGeneratorインタフェースはnext()メソッドの戻り値がパラメータのタイプであることを確認します.