forked from PacktPublishing/Java-Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMelonFactory.java
More file actions
50 lines (37 loc) · 1.33 KB
/
MelonFactory.java
File metadata and controls
50 lines (37 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package modern.challenge;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;
public final class MelonFactory {
private MelonFactory() {
throw new AssertionError("Cannot be instantiated");
}
private static final TriFunction<String, Integer, String, Melon> MELON = Melon::new;
private static final Map<String, Supplier<Fruit>> MELONS
= Map.of("Gac", Gac::new, "Hemi", Hemi::new, "Cantaloupe", Cantaloupe::new);
public static Fruit newInstance(String name, int weight, String color) {
return MELON.apply(name, weight, name);
}
public static Fruit newInstance(Class<?> clazz) {
Supplier<Fruit> supplier = MELONS.get(clazz.getSimpleName());
if (supplier == null) {
throw new IllegalArgumentException("Invalid clazz argument: " + clazz);
}
return supplier.get();
}
/*
public static Fruit newInstance(Class<?> clazz) {
switch (clazz.getSimpleName()) {
case "Gac":
return new Gac();
case "Hemi":
return new Hemi();
case "Cantaloupe":
return new Cantaloupe();
default:
throw new IllegalArgumentException("Invalid clazz argument: " + clazz);
}
}
*/
}