2015-09-07 11:44:36 -06:00
|
|
|
// generics/FactoryConstraint.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-01-25 18:05:55 -08:00
|
|
|
import java.util.*;
|
|
|
|
import java.util.function.*;
|
|
|
|
import onjava.*;
|
2015-06-15 17:47:35 -07:00
|
|
|
|
2016-01-25 18:05:55 -08:00
|
|
|
class IntegerFactory implements Supplier<Integer> {
|
|
|
|
private int i = 0;
|
|
|
|
@Override
|
|
|
|
public Integer get() {
|
|
|
|
return ++i;
|
|
|
|
}
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
|
|
|
|
2016-01-25 18:05:55 -08:00
|
|
|
class Widget {
|
|
|
|
private int id;
|
2017-05-01 14:33:10 -06:00
|
|
|
Widget(int n) { id = n; }
|
2016-01-25 18:05:55 -08:00
|
|
|
@Override
|
|
|
|
public String toString() {
|
|
|
|
return "Widget " + id;
|
|
|
|
}
|
|
|
|
public static
|
|
|
|
class Factory implements Supplier<Widget> {
|
|
|
|
private int i = 0;
|
|
|
|
@Override
|
|
|
|
public Widget get() { return new Widget(++i); }
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-01-25 18:05:55 -08:00
|
|
|
class Fudge {
|
|
|
|
private static int count = 1;
|
|
|
|
private int n = count++;
|
2015-06-15 17:47:35 -07:00
|
|
|
@Override
|
2016-01-25 18:05:55 -08:00
|
|
|
public String toString() { return "Fudge " + n; }
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
|
|
|
|
2016-01-25 18:05:55 -08:00
|
|
|
class Foo2<T> {
|
|
|
|
private List<T> x = new ArrayList<>();
|
2017-05-01 14:33:10 -06:00
|
|
|
Foo2(Supplier<T> factory) {
|
2016-01-25 18:05:55 -08:00
|
|
|
Suppliers.fill(x, factory, 5);
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
2016-01-25 18:05:55 -08:00
|
|
|
@Override
|
|
|
|
public String toString() { return x.toString(); }
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
public class FactoryConstraint {
|
|
|
|
public static void main(String[] args) {
|
2017-05-10 11:45:39 -06:00
|
|
|
System.out.println(
|
|
|
|
new Foo2<>(new IntegerFactory()));
|
|
|
|
System.out.println(
|
|
|
|
new Foo2<>(new Widget.Factory()));
|
|
|
|
System.out.println(
|
|
|
|
new Foo2<>(Fudge::new));
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|
2016-01-25 18:05:55 -08:00
|
|
|
/* Output:
|
|
|
|
[1, 2, 3, 4, 5]
|
|
|
|
[Widget 1, Widget 2, Widget 3, Widget 4, Widget 5]
|
|
|
|
[Fudge 1, Fudge 2, Fudge 3, Fudge 4, Fudge 5]
|
|
|
|
*/
|