简体   繁体   中英

Examples of singleton classes in the Java APIs

What are the best examples of the Singleton design pattern in the Java APIs? Is the 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.

Singleton Wiki Article

Java Dev on Singletons

Why Singletons are Evil

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM