问题
Possible Duplicate:
cracking singleton with other ways
Can anyone please tell me when a Singleton
would not work as a Singleton
?
回答1:
There is very good post published on Sun website by author Joshua Fox. Please go through this.
below are some of them scenario when your Singleton
doesn't behave like.
- Multiple Singletons in Two or More Virtual Machines
- Multiple Singletons Simultaneously Loaded by Different Class Loaders
- Singleton Classes Destroyed by Garbage Collection, then Reloaded
- Purposely Reloaded Singleton Classes
- Copies of a Singleton Object that has Undergone Serialization and Deserialization
回答2:
A singleton (in Java land) wouldn't work as a singleton if a given class is loaded by multiple class-loaders. Since a single class can exist (or can be loaded) in multiple classloaders, it's quite possible to have "multiple" instances of a "supposedly" singleton class for a given JVM instance. But this is a pretty rare case and doesn't happen a lot. :)
回答3:
If you are able to create more than one instance of the class then it doesn't remain singleton by using ways like cloning, De-serialization etc.
回答4:
Something like so would defy the purpose of the Singleton:
public class BadSingleton
{
private BadSingleton()
{
}
public BadSingleton getInstance()
{
return new BadSingleton();
}
}
The above will return a new instance of the BadSingleton
class everytime that the getInstance()
method is called. This will allow for various instances of the class which defies the purpose of the Singleton design pattern.
A similar scenario can also be achieved by using multiple class loaders (even if the Singleton is written correctly).
来源:https://stackoverflow.com/questions/11664076/when-would-a-singleton-not-work-as-a-singleton