65 lines
2.0 KiB
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// patterns/recyclea/RecycleA.java
// (c)2021 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.
// Recycling with reflection.
2016-07-28 12:48:23 -06:00
// {java patterns.recyclea.RecycleA}
2015-06-15 17:47:35 -07:00
package patterns.recyclea;
import java.util.*;
2015-11-03 12:00:44 -08:00
import java.util.function.*;
import java.util.stream.*;
import patterns.trash.*;
2015-06-15 17:47:35 -07:00
class SimpleFactory {
static final
List<Function<Double, Trash>> constructors =
2015-11-03 12:00:44 -08:00
Arrays.asList(
Aluminum::new, Paper::new, Glass::new);
static final int SIZE = constructors.size();
2017-01-08 22:55:49 -08:00
private static SplittableRandom rand =
new SplittableRandom(42);
public static Trash random() {
return constructors
.get(rand.nextInt(SIZE))
2015-11-03 12:00:44 -08:00
.apply(rand.nextDouble());
}
}
2015-06-15 17:47:35 -07:00
public class RecycleA {
public static void main(String[] args) {
2015-11-03 12:00:44 -08:00
List<Trash> bin =
Stream.generate(SimpleFactory::random)
.limit(10)
2015-11-03 12:00:44 -08:00
.collect(Collectors.toList());
Bins bins = new Bins(bin);
bins.show();
2015-06-15 17:47:35 -07:00
}
2015-09-07 11:44:36 -06:00
}
/* Output:
Aluminum weight: 0.34 * price: 1.67 = 0.57
Aluminum weight: 0.62 * price: 1.67 = 1.03
Aluminum weight: 0.49 * price: 1.67 = 0.82
Aluminum weight: 0.50 * price: 1.67 = 0.83
Total Aluminum value = 3.26
Paper weight: 0.69 * price: 0.10 = 0.07
Total Paper value = 0.07
Glass weight: 0.16 * price: 0.23 = 0.04
Glass weight: 0.87 * price: 0.23 = 0.20
Glass weight: 0.80 * price: 0.23 = 0.18
Glass weight: 0.52 * price: 0.23 = 0.12
Glass weight: 0.20 * price: 0.23 = 0.05
Total Glass value = 0.59
Total Cardboard value = 0.00
Glass weight: 0.16 * price: 0.23 = 0.04
Aluminum weight: 0.34 * price: 1.67 = 0.57
Glass weight: 0.87 * price: 0.23 = 0.20
Glass weight: 0.80 * price: 0.23 = 0.18
Aluminum weight: 0.62 * price: 1.67 = 1.03
Aluminum weight: 0.49 * price: 1.67 = 0.82
Glass weight: 0.52 * price: 0.23 = 0.12
Glass weight: 0.20 * price: 0.23 = 0.05
Aluminum weight: 0.50 * price: 1.67 = 0.83
Paper weight: 0.69 * price: 0.10 = 0.07
Total Trash value = 3.91
2015-09-07 11:44:36 -06:00
*/