- 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 in Java?
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
- Related Articles
- How to prevent Cloning to break a Singleton Class Pattern?
- How to prevent Reflection to break a Singleton Class Pattern?
- How to prevent Serialization to break a Singleton Class Pattern?
- How to make a class singleton in Java?\n
- How to implement a Singleton design pattern in C#?
- How to write a singleton class in C++?
- What is a singleton class in Java?
- How to use singleton class in android?
- How to prevent object of a class from garbage collection in Java?
- How to make a singleton enum in Java?
- Use Pattern class to match in Java
- Java Program to Show Shallow Cloning and Deep Cloning
- How to prevent class inheritance in C++
- How to refresh Singleton class every one hour in android?
- How to match a particular word in a string using Pattern class in Java?

Advertisements