-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy pathabstractfactory2.java
37 lines (29 loc) · 1 KB
/
abstractfactory2.java
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
package abstractfactory;
import java.util.HashMap;
import java.util.function.Supplier;
public interface abstractfactory2 {
interface Vehicle { }
record Bus(String color) implements Vehicle { }
record Car() implements Vehicle { }
class Registry {
private final HashMap<String, Supplier<? extends Vehicle>> map = new HashMap<>();
public void register(String name, Supplier<? extends Vehicle> supplier) {
map.put(name, supplier);
}
public Vehicle create(String name) {
return map.computeIfAbsent(name, n -> { throw new IllegalArgumentException("Unknown " + n); })
.get();
}
}
static void main(String[] args) {
var registry = new Registry();
registry.register("car", Car::new);
// as a singleton
var yellowBus = new Bus("yellow");
registry.register("bus", () -> yellowBus);
var vehicle1 = registry.create("bus");
System.out.println(vehicle1);
var vehicle2 = registry.create("car");
System.out.println(vehicle2);
}
}