Skip to content

Commit 46b23f3

Browse files
committed
Add Simple Factory Pattern implementation
Java source code demonstrate simple factory design pattern
1 parent 8afe4c3 commit 46b23f3

File tree

6 files changed

+84
-0
lines changed

6 files changed

+84
-0
lines changed

pom.xml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,7 @@
195195
<module>arrange-act-assert</module>
196196
<module>transaction-script</module>
197197
<module>filterer</module>
198+
<module>simple-factory</module>
198199
</modules>
199200

200201
<repositories>
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package com.iluwatar.simplefactory;
2+
3+
import org.slf4j.Logger;
4+
import org.slf4j.LoggerFactory;
5+
6+
public class App {
7+
8+
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
9+
10+
public static void main(String[] args) {
11+
Car car1 = CarSimpleFactory.getCar(CarSimpleFactory.carTypes.FORD);
12+
Car car2 = CarSimpleFactory.getCar(CarSimpleFactory.carTypes.FERRARI);
13+
LOGGER.info(car1.getDescription());
14+
LOGGER.info(car2.getDescription());
15+
}
16+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
package com.iluwatar.simplefactory;
2+
3+
/**
4+
* Car interface
5+
*/
6+
public interface Car {
7+
8+
public String getDescription();
9+
10+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package com.iluwatar.simplefactory;
2+
3+
4+
/**
5+
* Factory of cars
6+
*/
7+
public class CarSimpleFactory {
8+
9+
/*
10+
* Enumeration for different types of cars
11+
*/
12+
static enum carTypes {
13+
FORD, FERRARI
14+
};
15+
16+
/*
17+
* Factory method takes as parameter a car type and initiate the appropriate class
18+
*/
19+
public static Car getCar(carTypes type) {
20+
switch (type) {
21+
case FORD:
22+
return new Ford();
23+
case FERRARI:
24+
return new Ferrari();
25+
default:
26+
throw new IllegalArgumentException("Model not supported.");
27+
}
28+
}
29+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package com.iluwatar.simplefactory;
2+
3+
/**
4+
* Ferrari implementation
5+
*/
6+
public class Ferrari implements Car {
7+
8+
static final String DESCRIPTION = "This is Ferrari.";
9+
10+
@Override
11+
public String getDescription() {
12+
return DESCRIPTION;
13+
}
14+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package com.iluwatar.simplefactory;
2+
3+
/**
4+
* Ford implementation
5+
*/
6+
public class Ford implements Car {
7+
8+
static final String DESCRIPTION = "This is Ford.";
9+
10+
@Override
11+
public String getDescription() {
12+
return DESCRIPTION;
13+
}
14+
}

0 commit comments

Comments
 (0)