简体   繁体   中英

Is Java's Runtime class a proper example of a Singleton?

I have been reading about singleton pattern for a while now and when I searched for Singleton classes in Java language I found Runtime as an example but when I looked into the source I found a very basic Singleton implementation:

private static Runtime currentRuntime = new Runtime();
public static Runtime getRuntime() {
    return currentRuntime;
}
private Runtime() {}

Whereas on the internet there is a lot written about how a singleton class should be. What I wanted to know is which of the Java language classes is best fit as a Singleton class example and why?

Yes, that's a very basic singleton. It does what it's supposed to do with no special frills.

The examples you find on the internet usually describe a lazy initialized singleton with emphasis on the performance of getInstance() (ie avoid synchronized, don't allow creating multiple instances if multiple threads call getInstance() at the same time and so forth).

If you don't need lazy initialization it becomes very simple to create a singleton, as you can see with Runtime .

Finally, you can find a lot of things written about the singleton pattern (some of them misleading), but it doesn't really warrant it. It's not that interesting, some consider it an anti-pattern, and if you find yourself writing your own singletons a lot, you're probably doing something not quite right.

Extra finally, if you do think you need a lazily initialized singleton, the current standard implementation is with enum .

public enum MySingleton {
    INSTANCE

    public String getSarcasticMessage() {
        return "I'm a lazy loaded singleton, use me for everything!";
    }
}

MySingleton.INSTANCE.getSarcasticMessage();  // This is how to use it

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