-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAbstractFactoryJava8.java
More file actions
85 lines (57 loc) · 1.87 KB
/
AbstractFactoryJava8.java
File metadata and controls
85 lines (57 loc) · 1.87 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.function.Supplier;
/**
* Created by dmorales on 8/12/2015.
*/
public class AbstractFactoryJava8 {
public interface Vehicle {}
public static class Car implements Vehicle {
@Override
public String toString() {
return "Car";
}
}
public static class Car2 extends Car {
@Override
public String toString() {
return "car2";
}
}
public static class Moto implements Vehicle {
@Override
public String toString() {
return "Moto";
}
}
public static class VehicleFactory {
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.getOrDefault(name,
() -> { throw new IllegalArgumentException("Unkown " + name);})
.get();
}
}
public static void main(String[] args) {
VehicleFactory factory = new VehicleFactory();
factory.register("car", Car::new);
factory.register("car2", Car2::new);
factory.register("moto", Moto::new);
Moto moto = new Moto();
factory.register("moto2", () -> moto);
Vehicle vehicle1 = factory.create("car");
System.out.println(vehicle1);
Vehicle vehicle2 = factory.create("moto");
System.out.println(vehicle2);
// Vehicle vehicle3 = factory.create("doesntexist");
// System.out.println(vehicle3);
List<? extends Number> a = new ArrayList<>();
List<? super Vehicle> x = new ArrayList<>();
x.add(new Car());
x.add(new Car2());
}
}