-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFactoryDemo.java
More file actions
79 lines (70 loc) · 2.25 KB
/
FactoryDemo.java
File metadata and controls
79 lines (70 loc) · 2.25 KB
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
76
77
78
79
// Product interface
interface GamingPeripheral {
void use();
}
// Concrete product classes
class RazerKeyboard implements GamingPeripheral {
public void use() {
System.out.println("Typing on Razer keyboard");
}
}
class RazerMouse implements GamingPeripheral {
public void use() {
System.out.println("Clicking Razer mouse");
}
}
class RazerHeadset implements GamingPeripheral {
public void use() {
System.out.println("Playing sound on Razer headset");
}
}
class SteelSeriesKeyboard implements GamingPeripheral {
public void use() {
System.out.println("Typing on SteelSeries keyboard");
}
}
class SteelSeriesMouse implements GamingPeripheral {
public void use() {
System.out.println("Clicking SteelSeries mouse");
}
}
class SteelSeriesHeadset implements GamingPeripheral {
public void use() {
System.out.println("Playing sound on SteelSeries headset");
}
}
// Factory class
class PeripheralFactory {
public static GamingPeripheral createPeripheral(String type, String brand) {
if (brand.equalsIgnoreCase("Razer")) {
switch (type.toLowerCase()) {
case "keyboard":
return new RazerKeyboard();
case "mouse":
return new RazerMouse();
case "headset":
return new RazerHeadset();
}
} else if (brand.equalsIgnoreCase("SteelSeries")) {
switch (type.toLowerCase()) {
case "keyboard":
return new SteelSeriesKeyboard();
case "mouse":
return new SteelSeriesMouse();
case "headset":
return new SteelSeriesHeadset();
}
}
throw new IllegalArgumentException("Unknown type or brand");
}
}
public class FactoryDemo {
public static void main(String[] args) {
GamingPeripheral keyboard = PeripheralFactory.createPeripheral("keyboard", "Razer");
GamingPeripheral mouse = PeripheralFactory.createPeripheral("mouse", "Razer");
GamingPeripheral headset = PeripheralFactory.createPeripheral("headset", "SteelSeries");
keyboard.use();
mouse.use();
headset.use();
}
}