Skip to content

Commit a99f7bf

Browse files
committed
Added factory method example with car types
1 parent ede37bd commit a99f7bf

File tree

5 files changed

+47
-0
lines changed

5 files changed

+47
-0
lines changed
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
package com.iluwatar.factory.method.example;
2+
3+
public interface Car {
4+
void drive();
5+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package com.iluwatar.factory.method.example;
2+
3+
public class CarFactory {
4+
5+
public static Car createCar(String type) {
6+
if (type.equalsIgnoreCase("sports")) {
7+
return new SportsCar();
8+
} else if (type.equalsIgnoreCase("suv")) {
9+
return new SuvCar();
10+
} else {
11+
throw new IllegalArgumentException("Unknown car type: " + type);
12+
}
13+
}
14+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
package com.iluwatar.factory.method.example;
2+
3+
public class Main {
4+
public static void main(String[] args) {
5+
Car sports = CarFactory.createCar("sports");
6+
sports.drive();
7+
8+
Car suv = CarFactory.createCar("suv");
9+
suv.drive();
10+
}
11+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
package com.iluwatar.factory.method.example;
2+
3+
public class SportsCar implements Car {
4+
@Override
5+
public void drive() {
6+
System.out.println("Driving a sports car fast!");
7+
}
8+
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
package com.iluwatar.factory.method.example;
2+
3+
public class SuvCar implements Car {
4+
@Override
5+
public void drive() {
6+
System.out.println("Driving a comfortable SUV!");
7+
}
8+
}
9+

0 commit comments

Comments
 (0)