What are the best examples of Singleton Pattern in Java API? Is Runtime class a singleton?
Only two examples comes to mind:
See also:
Update: to answer PeterMmm's (currently deleted?) comment (which asked how I knew that it was a singleton), check the javadoc and source code:
public class Runtime {
private static Runtime currentRuntime = new Runtime();
/**
* Returns the runtime object associated with the current Java application.
* Most of the methods of class <code>Runtime</code> are instance
* methods and must be invoked with respect to the current runtime object.
*
* @return the <code>Runtime</code> object associated with the current
* Java application.
*/
public static Runtime getRuntime() {
return currentRuntime;
}
/** Don't let anyone else instantiate this class */
private Runtime() {}
It returns the same instance everytime and it has a private
constructor.
Note singletons should be used with care and reflection. Consider the arguments against singletons and your situation before you implement one. Overuse of singletons is an anti-pattern - similar to global variables.
I've used them in the past and see some benefit to them. I've also been highly annoyed when trying to do test driven development with them around that's one area where they are evil. Also inheriting from them results in some hard to understand behaviour - at least in Python - I don't know for sure in Java. Generally you just don't do it because of that. So like threading these seem like a great idea at first and then you run into the pitfalls and realize well maybe this isn't so good after all.
This is for Swing : SingleFrameApplication. Check out this presentation it wonderfully describes how does it work.