-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPrototype.java
76 lines (62 loc) · 1.87 KB
/
Prototype.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
76
// Prototype Interface
abstract class Car implements Cloneable {
protected String engine;
@Override
public Car clone() throws CloneNotSupportedException {
return (Car) super.clone();
}
public abstract void showDetails();
}
// Concrete Prototype - Sedan
class Sedan extends Car {
private int seats;
public Sedan(String engine, int seats) {
this.engine = engine;
this.seats = seats;
}
@Override
public Car clone() throws CloneNotSupportedException {
return (Sedan) super.clone();
}
@Override
public void showDetails() {
System.out.println("Sedan with engine: " + engine + ", seats: " + seats);
}
}
// Concrete Prototype - SUV
class SUV extends Car {
private boolean offroadCapability;
public SUV(String engine, boolean offroadCapability) {
this.engine = engine;
this.offroadCapability = offroadCapability;
}
@Override
public Car clone() throws CloneNotSupportedException {
return (SUV) super.clone();
}
@Override
public void showDetails() {
System.out.println("SUV with engine: " + engine + ", offroad capability: " + (offroadCapability ? "Yes" : "No"));
}
}
// Client code demonstrating prototype pattern
public class Prototype {
public static void main(String[] args) {
try {
// Original Sedan
Sedan sedan = new Sedan("V6", 5);
sedan.showDetails();
// Cloning the Sedan
Sedan clonedSedan = (Sedan) sedan.clone();
clonedSedan.showDetails();
// Original SUV
SUV suv = new SUV("V8", true);
suv.showDetails();
// Cloning the SUV
SUV clonedSUV = (SUV) suv.clone();
clonedSUV.showDetails();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}