updates :

- Using lambda expression to create cars
- Using spaces instead of tabs in pom.xml
This commit is contained in:
Samil Ayoub
2020-09-04 21:21:51 +01:00
parent 8b26452c75
commit 6caf78e4e5
6 changed files with 76 additions and 52 deletions

View File

@ -43,8 +43,8 @@ public class App {
* Program main entry point.
*/
public static void main(String[] args) {
var car1 = CarsFactory.getCar(CarsFactory.CarType.FORD);
var car2 = CarsFactory.getCar(CarsFactory.CarType.FERRARI);
var car1 = CarsFactory.getCar(CarType.FORD);
var car2 = CarsFactory.getCar(CarType.FERRARI);
LOGGER.info(car1.getDescription());
LOGGER.info(car2.getDescription());
}

View File

@ -0,0 +1,22 @@
package com.iluwatar.factory;
import java.util.function.Supplier;
public enum CarType {
/**
* Enumeration for different types of cars.
*/
FORD(Ford::new),
FERRARI(Ferrari::new);
private final Supplier<Car> constructor;
CarType(Supplier<Car> constructor) {
this.constructor = constructor;
}
public Supplier<Car> getConstructor() {
return this.constructor;
}
}

View File

@ -5,21 +5,10 @@ package com.iluwatar.factory;
*/
public class CarsFactory {
/**
* Enumeration for different types of cars.
*/
static enum CarType {
FORD, FERRARI
}
/**
* Factory method takes as parameter a car type and initiate the appropriate class.
*/
public static Car getCar(CarType type) {
switch (type) {
case FORD: return new Ford();
case FERRARI: return new Ferrari();
default: throw new IllegalArgumentException("Model not supported.");
}
return type.getConstructor().get();
}
}

View File

@ -8,7 +8,7 @@ class CarsFactoryTest {
@Test
void shouldReturnFerrariInstance() {
final var ferrari = CarsFactory.getCar(CarsFactory.CarType.FERRARI);
final var ferrari = CarsFactory.getCar(CarType.FERRARI);
assertTrue(ferrari instanceof Ferrari);
}