-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFactoryDesignPattern.java
More file actions
38 lines (33 loc) · 972 Bytes
/
FactoryDesignPattern.java
File metadata and controls
38 lines (33 loc) · 972 Bytes
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
// Interface
interface Transport {
void deliver();
}
// Two types of transport
class Truck implements Transport {
public void deliver() {
System.out.println("Delivering by Truck");
}
}
class Ship implements Transport {
public void deliver() {
System.out.println("Delivering by Ship");
}
}
// Factory that creates transport objects
class TransportFactory {
public Transport getTransport(String type) {
if (type.equalsIgnoreCase("truck")) return new Truck();
else if (type.equalsIgnoreCase("ship")) return new Ship();
else return null;
}
}
// Client code
public class Main {
public static void main(String[] args) {
TransportFactory factory = new TransportFactory();
Transport t1 = factory.getTransport("truck");
t1.deliver(); // Output: Delivering by Truck
Transport t2 = factory.getTransport("ship");
t2.deliver(); // Output: Delivering by Ship
}
}