Add Simple Factory Pattern implementation

Java source code demonstrate simple factory design pattern
This commit is contained in:
Samil Ayoub 2020-09-02 13:46:53 +01:00
parent 8afe4c314a
commit 46b23f322f
6 changed files with 84 additions and 0 deletions

View File

@ -195,6 +195,7 @@
<module>arrange-act-assert</module>
<module>transaction-script</module>
<module>filterer</module>
<module>simple-factory</module>
</modules>
<repositories>

View File

@ -0,0 +1,16 @@
package com.iluwatar.simplefactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class App {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
public static void main(String[] args) {
Car car1 = CarSimpleFactory.getCar(CarSimpleFactory.carTypes.FORD);
Car car2 = CarSimpleFactory.getCar(CarSimpleFactory.carTypes.FERRARI);
LOGGER.info(car1.getDescription());
LOGGER.info(car2.getDescription());
}
}

View File

@ -0,0 +1,10 @@
package com.iluwatar.simplefactory;
/**
* Car interface
*/
public interface Car {
public String getDescription();
}

View File

@ -0,0 +1,29 @@
package com.iluwatar.simplefactory;
/**
* Factory of cars
*/
public class CarSimpleFactory {
/*
* Enumeration for different types of cars
*/
static enum carTypes {
FORD, FERRARI
};
/*
* Factory method takes as parameter a car type and initiate the appropriate class
*/
public static Car getCar(carTypes type) {
switch (type) {
case FORD:
return new Ford();
case FERRARI:
return new Ferrari();
default:
throw new IllegalArgumentException("Model not supported.");
}
}
}

View File

@ -0,0 +1,14 @@
package com.iluwatar.simplefactory;
/**
* Ferrari implementation
*/
public class Ferrari implements Car {
static final String DESCRIPTION = "This is Ferrari.";
@Override
public String getDescription() {
return DESCRIPTION;
}
}

View File

@ -0,0 +1,14 @@
package com.iluwatar.simplefactory;
/**
* Ford implementation
*/
public class Ford implements Car {
static final String DESCRIPTION = "This is Ford.";
@Override
public String getDescription() {
return DESCRIPTION;
}
}