-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSingletonCloningPreventExample.java
58 lines (45 loc) · 1.83 KB
/
SingletonCloningPreventExample.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
package com.javaexperiments;
/**
* By explicitly throwing CloneNotSupported exception from the clone()
* would prevent object creation the second time, thereby preventing
* the breaking of Singleton Pattern
*/
public class SingletonCloningPreventExample extends SuperCloneableClass {
private static SingletonCloningPreventExample single_instance = null;
// Making the constructor as private
private SingletonCloningPreventExample() {
}
/**
* Static method to create instance of Singleton class
*
* @return single object of 'SingletonCloningExample' class
*/
public static SingletonCloningPreventExample getInstance() {
// Ensuring only one instance is created
if (single_instance == null) single_instance = new SingletonCloningPreventExample();
return single_instance;
}
public static void main(String[] args) throws CloneNotSupportedException {
// Instantiating SingletonCloningExample class with variable 'objectOne'
SingletonCloningPreventExample objectOne = SingletonCloningPreventExample.getInstance();
// Cloning the 'objectOne' using clone()
SingletonCloningPreventExample objectTwo = (SingletonCloningPreventExample) objectOne.clone();
/**
* Checking the hashCode for both the objects which would be same,
* meaning the objects are same
*/
System.out.println("Hashcode of Object 1 - " + objectOne.hashCode());
System.out.println("Hashcode of Object 2 - " + objectTwo.hashCode());
}
// Override the clone() to throw the same instance
@Override
protected Object clone() {
return single_instance;
}
}
class SuperCloneableClass implements Cloneable {
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}