-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Description
Features (wiki):
An implementation of the singleton pattern must:
- ensure that only one instance of the singleton class ever exists;
- and provide global access to that instance.
Typically, this is done by:
- declaring all constructors of the class to be private;
- and providing a static method that returns a reference to the instance.
The instance is usually stored as a private static variable; the instance is created when the variable is initialized, at some point before the static method is first called.
(Almost) Best Practices:
1. private static internal holder:
public class Singleton {
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
private Singleton (){}
public static final Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}The intuitive implementation has thread safety problems (wrong examples, see ref.) This implementation using JVM mechanism itself guarantee the thread safety issue:
SingletonHolderis private, there is no access exceptgetInstance(), therefore it's lazy initialization;- Meanwhile no synchronizing when reading the instance, prevent from a poor performance;
- No depandance to any specific JDK version.
2. enum typed class
public enum Singleton{
INSTANCE;
}A real elegant implementation. Access from EasySingleton.INSTANCE, easier than calling getInstance() as above.
Creating a enum instance is thread-safe by default, so no thread safety issue. But thread safety of any other method is responsible to programmer himself.
还有防止上面的通过反射机制调用私用构造器。
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels