There is a clone() method defined in the java.lang.Object class which TestSingleton is inherited from.
By default, the clone() method is marked as protected, but if your TestSingleton extends another class
that does support cloning, it is possible to violate the design principles of the singleton.
So,we must add a clone() method of our own, and throw a CloneNotSupportedException ! for 100% certain that TestSingleton is a singleton
so we can modify it like this
nancy andrew wrote:I was recently asked this question: Create a singleton class which returns same object of that class itself everytime.
I know singleton class looks like this:
But i should not use a new operator like instance = new TestSingleton(); In short, my program should return same instance of same class everytime. Any pointers??
You have to use the new operator once to create the single instance that you are going to return every time for all future calls to getInstance.
Your code is generally correct although it could have problems in a multithreaded environment. You need to either make your getInstance method synchronized or initialise the instance variable at the same time as you declare it.
Search these forums for examples of how it should be done.
Seetharaman Venkatasamy wrote:....
additionally, *use double-check technique* instead of adding a synchronized key word infornt of getInstance method's modifier. ....
Seetharaman, double-check technique is bad. Specially when it is used with any version upto Java 1.4. It gives you false feeling that code is thread safe but it is not. However 1.5 modified the way objects are created and hence made double-check safe. But if you don't want your code version dependent, use method mentioned by "Joanne Neal". They are in a way fool-proof (of couse they are NOT 100% as reflection and manipulation with classloader instance allows multiple instances of singleton).