2015-11-03 12:00:44 -08:00
|
|
|
// generics/coffee/CoffeeSupplier.java
|
2016-12-30 17:23:13 -08:00
|
|
|
// (c)2017 MindView LLC: see Copyright.txt
|
2015-11-15 15:51:35 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
2016-09-23 13:23:35 -06:00
|
|
|
// Visit http://OnJava8.com for more book information.
|
2016-07-28 12:48:23 -06:00
|
|
|
// {java generics.coffee.CoffeeSupplier}
|
2015-06-15 17:47:35 -07:00
|
|
|
package generics.coffee;
|
|
|
|
import java.util.*;
|
2015-11-03 12:00:44 -08:00
|
|
|
import java.util.function.*;
|
2016-01-25 18:05:55 -08:00
|
|
|
import java.util.stream.*;
|
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) {
|
2016-01-25 18:05:55 -08:00
|
|
|
Stream.generate(new CoffeeSupplier())
|
|
|
|
.limit(5)
|
|
|
|
.forEach(System.out::println);
|
2015-11-03 12:00:44 -08:00
|
|
|
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
|
|
|
*/
|