2015-11-03 12:00:44 -08:00
|
|
|
// generics/coffee/CoffeeSupplier.java
|
2015-06-15 17:47:35 -07:00
|
|
|
// Generate different types of Coffee:
|
|
|
|
package generics.coffee;
|
|
|
|
import java.util.*;
|
2015-11-03 12:00:44 -08:00
|
|
|
import java.util.function.*;
|
2015-06-15 17:47:35 -07:00
|
|
|
|
2015-11-03 12:00:44 -08:00
|
|
|
public class CoffeeSupplier
|
|
|
|
implements Supplier<Coffee>, Iterable<Coffee> {
|
2015-06-15 17:47:35 -07:00
|
|
|
private Class<?>[] types = { Latte.class, Mocha.class,
|
|
|
|
Cappuccino.class, Americano.class, Breve.class, };
|
|
|
|
private static Random rand = new Random(47);
|
2015-11-03 12:00:44 -08:00
|
|
|
public CoffeeSupplier() {}
|
2015-06-15 17:47:35 -07:00
|
|
|
// For iteration:
|
|
|
|
private int size = 0;
|
2015-11-03 12:00:44 -08:00
|
|
|
public CoffeeSupplier(int sz) { size = sz; }
|
2015-06-15 17:47:35 -07:00
|
|
|
@Override
|
2015-11-03 12:00:44 -08:00
|
|
|
public Coffee get() {
|
2015-06-15 17:47:35 -07:00
|
|
|
try {
|
|
|
|
return (Coffee)
|
|
|
|
types[rand.nextInt(types.length)].newInstance();
|
|
|
|
// Report programmer errors at run time:
|
|
|
|
} catch(InstantiationException |
|
|
|
|
IllegalAccessException e) {
|
|
|
|
throw new RuntimeException(e);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
class CoffeeIterator implements Iterator<Coffee> {
|
|
|
|
int count = size;
|
|
|
|
@Override
|
|
|
|
public boolean hasNext() { return count > 0; }
|
|
|
|
@Override
|
|
|
|
public Coffee next() {
|
|
|
|
count--;
|
2015-11-03 12:00:44 -08:00
|
|
|
return CoffeeSupplier.this.get();
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
|
|
|
@Override
|
|
|
|
public void remove() { // Not implemented
|
|
|
|
throw new UnsupportedOperationException();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
@Override
|
|
|
|
public Iterator<Coffee> iterator() {
|
|
|
|
return new CoffeeIterator();
|
|
|
|
}
|
|
|
|
public static void main(String[] args) {
|
2015-11-03 12:00:44 -08:00
|
|
|
CoffeeSupplier gen = new CoffeeSupplier();
|
2015-06-15 17:47:35 -07:00
|
|
|
for(int i = 0; i < 5; i++)
|
2015-11-03 12:00:44 -08:00
|
|
|
System.out.println(gen.get());
|
|
|
|
for(Coffee c : new CoffeeSupplier(5))
|
2015-06-15 17:47:35 -07:00
|
|
|
System.out.println(c);
|
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|
|
|
|
/* Output:
|
2015-06-15 17:47:35 -07:00
|
|
|
Americano 0
|
|
|
|
Latte 1
|
|
|
|
Americano 2
|
|
|
|
Mocha 3
|
|
|
|
Mocha 4
|
|
|
|
Breve 5
|
|
|
|
Americano 6
|
|
|
|
Latte 7
|
|
|
|
Cappuccino 8
|
|
|
|
Cappuccino 9
|
2015-09-07 11:44:36 -06:00
|
|
|
*/
|