-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrototypeTest.java
More file actions
68 lines (51 loc) · 1.29 KB
/
PrototypeTest.java
File metadata and controls
68 lines (51 loc) · 1.29 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
/*
A Creational Pattern.
Specify the kind of objects to create using a prototypical instance,
and create new objects by copying this prototype
*/
public class PrototypeTest {
public static void main(String[] args){
System.out.println("-------------- PROTOTYPE ---------------");
PrototypeColor c1 = new Color("Red", 255, 0, 0);
PrototypeColor c2 = c1.cloneMe();
System.out.println("c1: "+c1.get());
c2.set("Green", 0, 255, 0);
System.out.println("c2: "+c2.get());
System.out.println("c1: "+c1.get());
}
}
// Prototype
abstract class PrototypeColor implements Cloneable {
String name = null;
int red;
int green;
int blue;
public abstract PrototypeColor cloneMe();
public String get(){
return "Color: "+name+" [R:"+red+", G:"+green+", B:"+blue+"]";
}
public void set(String str, int r, int g, int b){
name = str;
red = r;
green = g;
blue = b;
}
}
// Concrete prototype
class Color extends PrototypeColor {
Color(String str, int r, int g, int b){
name = str;
red = r;
green = g;
blue = b;
}
public PrototypeColor cloneMe(){
try{
return (PrototypeColor)this.clone();
}
catch(CloneNotSupportedException cns){
System.out.println(cns.getMessage());
}
return null;
}
}