-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSingletonPreventClone.java
More file actions
38 lines (31 loc) · 1.06 KB
/
Copy pathSingletonPreventClone.java
File metadata and controls
38 lines (31 loc) · 1.06 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
package Misc;
// Java code to explain cloning
// issue with singleton
class SuperClass implements Cloneable {
int i = 10;
@Override
protected Object clone()
throws CloneNotSupportedException {
return super.clone(); //By this we can break and clone the singleton instance.
//throw new CloneNotSupportedException(); //by this we can prevent from clonneable.
}
}
// Singleton class
class Singleton extends SuperClass {
// public instance initialized when loading the class
public static Singleton instance = new Singleton();
private Singleton() {
// private constructor
}
}
public class SingletonPreventClone {
public static void main(String[] args)
throws CloneNotSupportedException {
Singleton instance1 = Singleton.instance;
Singleton instance2 = (Singleton) instance1.clone();
System.out.println("instance1 hashCode:- "
+ instance1.hashCode());
System.out.println("instance2 hashCode:- "
+ instance2.hashCode());
}
}