updates :
- Using lambda expression to create cars - Using spaces instead of tabs in pom.xml
This commit is contained in:
@ -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());
|
||||
}
|
||||
|
22
factory/src/main/java/com/iluwatar/factory/CarType.java
Normal file
22
factory/src/main/java/com/iluwatar/factory/CarType.java
Normal 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;
|
||||
}
|
||||
}
|
@ -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();
|
||||
}
|
||||
}
|
||||
|
@ -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);
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user