wood burning stoves 2.0*
The moose likes Java in General and the fly likes singleton.clone() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "singleton.clone()" Watch "singleton.clone()" New topic
Author

singleton.clone()

nareshk kumar
Greenhorn

Joined: Sep 22, 2005
Posts: 4
what happend if we apply the clone methode on singleton object?

already i tried , prob is :

as per my knowledge we can apply the clone methode on any class object which is implements clonneable interface.but in case of singleton it is giving like clone() "methode having protected access",why this is comming for singleton class only,(actually singleton means some design pattern, we r not using any predefind interfaces are keywords)
Sanju Thomas
Ranch Hand

Joined: Dec 29, 2004
Posts: 243
When you try to invoke clone() any object of your class (whether singleton or normal), the clone() method from the Object class is actually invoked (since your class extends the Object class). The clone() method have protected access in the Object class. That is why you get that error message.
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
This question came up recently. I wonder if it's something in a text book or class somewhere.

The singleton pattern usually means you want to restrict a class to exactly one instance. If the design seriously requires one instance you'd want to prohibit clone, maybe even override the method to throw an exception.

The mechanism for singleton is not specified in the pattern. The private constructor with static factory method solution is common, but not required. You can find another way to restrict creation and still allow clone if you really have to.
[ September 29, 2005: Message edited by: Stan James ]

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
nareshk kumar
Greenhorn

Joined: Sep 22, 2005
Posts: 4
Thank you very much for ur reply

naresh


Originally posted by Stan James:
This question came up recently. I wonder if it's something in a text book or class somewhere.

The singleton pattern usually means you want to restrict a class to exactly one instance. If the design seriously requires one instance you'd want to prohibit clone, maybe even override the method to throw an exception.

The mechanism for singleton is not specified in the pattern. The private constructor with static factory method solution is common, but not required. You can find another way to restrict creation and still allow clone if you really have to.

[ September 29, 2005: Message edited by: Stan James ]
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
Originally posted by Stan James:
This question came up recently. I wonder if it's something in a text book or class somewhere.

The singleton pattern usually means you want to restrict a class to exactly one instance. If the design seriously requires one instance you'd want to prohibit clone, maybe even override the method to throw an exception.

The mechanism for singleton is not specified in the pattern. The private constructor with static factory method solution is common, but not required. You can find another way to restrict creation and still allow clone if you really have to.

[ September 29, 2005: Message edited by: Stan James ]


clone() is restricted to protected access by default. I guess this isn't a completely solution however, since someone can extend your Singleton class and override clone(). Also other classes in the same package will be able to call clone(). It seems like it would be safest to override it with private access so it cannot be called by other classes. Of course, then someone might try to use the Reflection API. Throwing an exception seems like a decent solution to avoid this problem.

Layne


Java API Documentation
The Java Tutorial
Mr. C Lamont Gilbert
Ranch Hand

Joined: Oct 05, 2001
Posts: 1170

Originally posted by Layne Lund:


clone() is restricted to protected access by default. I guess this isn't a completely solution however, since someone can extend your Singleton class and override clone(). Also other classes in the same package will be able to call clone(). It seems like it would be safest to override it with private access so it cannot be called by other classes. Of course, then someone might try to use the Reflection API. Throwing an exception seems like a decent solution to avoid this problem.

Layne


you cant override to be more restrictive, only more permissive.
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
Originally posted by Mr. C Lamont Gilbert:


you cant override to be more restrictive, only more permissive.


Ooops. Thanks for catching my mistake there. So I guess you DO have to throw an exception to make it so a Singleton cannot be cloned. As another safety precation, you can declare the class as final so it cannot be extended.

Layne
Sanju Thomas
Ranch Hand

Joined: Dec 29, 2004
Posts: 243
Still I can hard clone it.
Paul Sturrock
Bartender

Joined: Apr 14, 2004
Posts: 10336

How? If the class is declared final and does not implement the clone method calling singleton.clone() will not compile.


JavaRanch FAQ HowToAskQuestionsOnJavaRanch
Sanju Thomas
Ranch Hand

Joined: Dec 29, 2004
Posts: 243
I was talking about deep cloning.
Paul Sturrock
Bartender

Joined: Apr 14, 2004
Posts: 10336

I still don't see how you could do this. The common way to do a deep clone is to serialize the object, write it to an OutputStream, and read it into an InputStream, creating the new object with this. If your singleton is final and doesn't implement Serializable that can't be done. Are you thinking of performing a deep clone some other way?

You could create more than one instance of a singleton using Reflection I think. But then a developer would have to purposefully ignore the fact this class is a singleton and presumably is documented as such. Used normally though you can guarentee there will only be one instance of this class per JVM.
[ October 05, 2005: Message edited by: Paul Sturrock ]
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
The singleton antipattern should be avoided.
Typically, a better solution is simply to pass a callback to obtain the instance(s) of the required type, but this typically depends on the appropriate abstraction for the domain, of which a singleton (usually, actually a class loader global) never is.


Tony Morris
Java Q&A (FAQ, Trivia)
Julien Grenier
Ranch Hand

Joined: Sep 01, 2005
Posts: 41

You could create more than one instance of a singleton using Reflection I think. But then a developer would have to purposefully ignore the fact this class is a singleton and presumably is documented as such. Used normally though you can guarentee there will only be one instance of this class per JVM.


Actually the only way to achieve that is to use Reflection within the Singleton Class, if not that's not possible since the Constructor is private (by Singleton definition).

like in this example :

But then you are purposly being dumb if you code something like that.

Trying to pull something like that outside the Singleton class result to the following Runtime-error :

java.lang.IllegalAccessException: Class Main can not access a member of class Singleton with modifiers "private"
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

Before you say this is impossible, have a look at the "setAccessible()" method that Constructor, Method, and Field inherit from AccessibleObject.


[Jess in Action][AskingGoodQuestions]
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
Originally posted by Ernest Friedman-Hill:
Before you say this is impossible, have a look at the "setAccessible()" method that Constructor, Method, and Field inherit from AccessibleObject.


This is why constructors should declare to throw an exception, such as UnsupportedOperationException. Certainly not an elegant solution, but the optimal workaround to the broken constructor semantics of the language.
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Constructor is private (by Singleton definition)


I love to throw a wrench in the works now and then ... says who? Private constructor is one common way to implement singleton but not the only one.

This whole question is probably framed badly. A singleton has one instance (or a controlled number and a controlled creation mechanism) so preventing cloning would probably be a design goal and we should look for ways to prevent cloning rather than doing it.

If cloning is a requirement call it almost-a-singleton, implement clone and Bob's your uncle.

Maybe the question is how to clone something that somebody else tried to prevent you from cloning by making a private constructor. Can't say it sounds like a good idea outside of an academic discussion, but sometimes it is fun to find a way around things.

I view the kind of reflection and changing accessibility above as "cheating" and don't really try to create designs to prevent cheating. If coders are willing to go to these lengths to violate the intent of the design it's pretty hard to stop them from making a mess.
[ October 05, 2005: Message edited by: Stan James ]
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608

I love to throw a wrench in the works now and then ... says who?

Says the language specification unfortunately. The 'new' keyword is guaranteed to return a new instance. Are you referring to the fact that 'private constructors' and 'singleton (anti)pattern' are not intrinsically tied concepts outside the context of Java? Within the context of Java, it certainly is as per 'constructors return new instance per invocation'.
Mr. C Lamont Gilbert
Ranch Hand

Joined: Oct 05, 2001
Posts: 1170

clone is a facility, it is not a defined method. it has no contract. So when someone calls clone they must have expectations about what it will do based on the API provided. If the API already states the object is a singleton, one would expect clone() to not be there at all. Why add clone in the first place?
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
Better still, why use Object.clone()? It's of a poor design that is easily duplicated more correctly.
Julien Grenier
Ranch Hand

Joined: Sep 01, 2005
Posts: 41
Before you say this is impossible, have a look at the "setAccessible()" method that Constructor, Method, and Field inherit from AccessibleObject.


I had a look at it. It took me some time to figure how to make it work (my problem was how to get an instance of the cTor (the getConstructors() only returns the public constructors but I found the getDeclaredConstructors() which returns everything). Well I guess I'll go to bed less stupid tonight.
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
The GoF pattern for Singleton talks about having a mechanism to control creation of a single instance or a controlled number of instances (that >1 may have come from another source). Private constructor is not the only mechanism available to us. Think of some other ways to hide concrete implementations of a public interface so nobody outside the package can do a new.

I hinted at an offshoot topic before ... how much do you enable a good design and how much do you enforce it? I've felt painted into a corner by frameworks and designs that try to control too much. I've also been disappointed that systems I've turned over to others rapidly lost the original design direction.
Mr. C Lamont Gilbert
Ranch Hand

Joined: Oct 05, 2001
Posts: 1170

Originally posted by Tony Morris:
Better still, why use Object.clone()? It's of a poor design that is easily duplicated more correctly.


What do you mean?
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
Originally posted by Mr. C Lamont Gilbert:


What do you mean?


Have you taken a look at how the API has been implemented? Granted, it's a very typical thing to do, but that doesn't validate it. Does it make sense to you to have an interface with no operations defined, and a protected method specified implicitly on all types always?

From another perspective, can you think of any other core API that is less broken (luckily, some exist), but with the same simplicity (one single interface operation) where so many questions are asked due to confusion?
Sanju Thomas
Ranch Hand

Joined: Dec 29, 2004
Posts: 243
Now what is the conclusion ?
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: singleton.clone()
 
Similar Threads
some doubts in core java
Cloning a Singleton Object
Singleton Class
Singleton object creation using clone
need clear solution