简体   繁体   中英

Singleton Design Pattern Implementation

I saw a different variety of implementations of Singleton Class. However, this particular implementation : https://sourcemaking.com/design_patterns/singleton/java/1 does not create the object in a private constructor.

Can someone explain, what the advantages or disadvantages between the two implementations would be ? The description given is minimal and I have not understood much from it.

Thanks.

The link you provided explains it very well, if succinctly... but let me try to expand...

The inner class is referenced no earlier (and therefore loaded no earlier by the class loader) than the moment that getInstance() is called.

This is the most important part of the explanation.

The inner class the above text is referring to is the SingletonHolder class, which exists solely for the purpose of holding an instance of Singleton .

Because this class is private and not referred to anywhere else, it is guaranteed that this class will not be initialized (loaded by the Java ClassLoader) until the getInstance() method of Singleton is called, because that's the earliest a JVM is required to initialize that class.

When a class is initialized, any static final fields (and static blocks) it contains are initialized before the class is made available to any user code. This initialization is thread-safe, so the code using this pattern does not need any of the complicated synchronization logic you will typically find in other implementations of the singleton pattern in Java.

See this question for more discussions about alternative implementations, including the enum based solution as well as the more complicated, explicitly synchronized versions of Singleton.

Notice that if you don't care about making your singleton lazy-loaded (ie. only initialized when needed), then just use the simplest possible way:

class Singleton {
    public static final INSTANCE = new Singleton();
    private Singleton() { /* cannot be instantiated externally */ }
}

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