- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to prevent Cloning to break a Singleton Class Pattern?
A Singleton pattern states that a class can have a single instance and multiple instances are not permitted to be created. For this purpose, we make the constructor of the class a private and return a instance via a static method. But using cloning, we can still create multiple instance of a class. See the example below −
Example - Breaking Singleton
public class Tester{ public static void main(String[] args) throws CloneNotSupportedException { A a = A.getInstance(); A b = (A)a.clone(); System.out.println(a.hashCode()); System.out.println(b.hashCode()); } } class A implements Cloneable { private static A a; private A(){} public static A getInstance(){ if(a == null){ a = new A(); } return a; } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } }
Output
705927765 366712642
Here you can see, we've created another object of a Singleton class. Let's see how to prevent such a situation −
Return the same object in the clone method as well.
Example - Protecting Singleton
@Override protected Object clone() throws CloneNotSupportedException { return getInstance(); }
Output
705927765 705927765
Advertisements