-
Notifications
You must be signed in to change notification settings - Fork 0
/
TestApp.java
99 lines (81 loc) · 2.64 KB
/
TestApp.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package com.ysingh.creational.singleton.destroy;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class TestApp {
public static void main(String[] args) {
System.out.println("Using Reflection: ");
try {
usingReflection();
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println();
System.out.println("Using Serialization: ");
try {
usingSerialization();
} catch(Exception ex) {
ex.printStackTrace();
}
System.out.println();
System.out.println("Using Clonable: ");
try {
usingClonable();
} catch(Exception ex) {
ex.printStackTrace();
}
}
private static void usingReflection() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Singleton instance1 = Singleton.getInstance();
Singleton instance2 = null;
Constructor<?>[] declaredConstructors = Singleton.class.getDeclaredConstructors();
for(Constructor<?> declaredConstructor : declaredConstructors) {
declaredConstructor.setAccessible(true);
instance2 = (Singleton)declaredConstructor.newInstance();
break;
}
System.out.println(instance1.hashCode());
System.out.println(instance2.hashCode());
}
private static void usingSerialization() throws IOException {
SerializableSingleton instance1 = SerializableSingleton.getInstance();
SerializableSingleton instance2 = null;
ObjectOutput objectOutput = null;
try {
objectOutput = new ObjectOutputStream(new FileOutputStream("singleton.ser"));
objectOutput.writeObject(instance1);
objectOutput.flush();
} catch(Exception ex) {
ex.printStackTrace();
} finally {
if(objectOutput != null) {
objectOutput.close();
}
}
ObjectInput objectInput = null;
try {
objectInput = new ObjectInputStream(new FileInputStream("singleton.ser"));
instance2 = (SerializableSingleton)objectInput.readObject();
} catch(Exception ex) {
ex.printStackTrace();
} finally {
if(objectInput != null) {
objectInput.close();
}
}
System.out.println(instance1.hashCode());
System.out.println(instance2.hashCode());
}
private static void usingClonable() throws CloneNotSupportedException {
ClonableSingleton instance1 = ClonableSingleton.getInstance();
ClonableSingleton instance2 = (ClonableSingleton) instance1.clone();
System.out.println(instance1.hashCode());
System.out.println(instance2.hashCode());
}
}