-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFactoryMethodExample.java
76 lines (63 loc) · 1.77 KB
/
FactoryMethodExample.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package com.javaexperiments;
import java.util.Scanner;
public class FactoryMethodExample {
public static void main(String[] args) {
System.out.println("Enter the type of car:\nAudi \nTesla");
Scanner in = new Scanner(System.in);
String carType = in.nextLine();
/**
* The factory method is called to get the object of the concrete classes by passing
* the information of the car from the user.
*/
CarFactory carFactory = new CarFactory();
carFactory.manufactureCar(carType.toLowerCase());
}
}
/**
* Abstract Class with abstract and concrete method
*/
abstract class Car {
public abstract void addEngineType();
public void deliverCar() {
System.out.println("Your car will be delivered at your doorstep.");
}
}
/**
* Concrete class 'AudiCar' extending the abstract Class
*/
class AudiCar extends Car {
@Override
public void addEngineType() {
System.out.println("You have ordered a car with gasoline Engine.");
}
}
/**
* Concrete class 'TeslaCar' extending the abstract Class
*/
class TeslaCar extends Car {
@Override
public void addEngineType() {
System.out.println("You have ordered a car with electric Engine. ");
}
}
/**
* In Factory method, the object of the Car is created.
*/
class CarFactory {
public Car manufactureCar(String type){
Car car;
switch (type.toLowerCase())
{
case "audi":
car = new AudiCar();
break;
case "tesla":
car = new TeslaCar();
break;
default: throw new IllegalArgumentException("No such car available.");
}
car.addEngineType();
car.deliverCar();
return car;
}
}