@@ -68,41 +68,52 @@ public class Ferrari implements Car {
6868}
6969```
7070
71- Then we have the static method "getCar" to create car objects encapsulated in the factory class "CarSimpleFactory" .
71+ Enumeration above represents types of cars that we support(Ford and Ferrari) .
7272
7373``` java
74- /**
75- * Factory of cars.
76- */
77- public class CarSimpleFactory {
74+ public enum CarType {
7875
7976 /**
8077 * Enumeration for different types of cars.
8178 */
82- static enum CarType {
83- FORD , FERRARI
79+ FORD (Ford :: new ),
80+ FERRARI (Ferrari :: new );
81+
82+ private final Supplier<Car > constructor;
83+
84+ CarType(Supplier<Car > constructor) {
85+ this . constructor = constructor;
86+ }
87+
88+ public Supplier<Car > getConstructor() {
89+ return this . constructor;
8490 }
91+ }
92+ ```
93+ Then we have the static method " getCar" to create car objects encapsulated in the factory class " CarSimpleFactory" .
94+
95+ ```java
96+ /**
97+ * Factory of cars.
98+ */
99+ public class CarsFactory {
85100
86101 /**
87102 * Factory method takes as parameter a car type and initiate the appropriate class.
88103 */
89104 public static Car getCar (CarType type ) {
90- switch (type) {
91- case FORD : return new Ford ();
92- case FERRARI : return new Ferrari ();
93- default : throw new IllegalArgumentException (" Model not supported." );
94- }
105+ return type. getConstructor(). get();
95106 }
96107}
97108```
98109
99- Now on the client code we can create differentes types of cars(Ford or Ferrari) using the factory class.
110+ Now on the client code we can create different types of cars using the factory class.
100111
101112```java
102- Car car1 = CarSimpleFactory . getCar(CarSimpleFactory . CarType . FORD );
103- Car car2 = CarSimpleFactory . getCar(CarSimpleFactory . CarType . FERRARI );
113+ var car1 = CarsFactory . getCar(CarType . FORD );
114+ var car2 = CarsFactory . getCar(CarType . FERRARI );
104115LOGGER . info(car1. getDescription());
105- LOGGER . info(car2. getDescription());
116+ LOGGER . info(car2. getDescription());;
106117```
107118
108119Program output:
0 commit comments