# What is a singleton?
- There are situations where exactly one object of a particula type is needed.
- Where it would be bad to have any more than one object of a particular class.
- Device drivers, registry setting manager, or other system - wide shared objects are the classic examples.
- Singleton objects also make sense where the state of an object consumes a lot of memory, and just one version of that state is sufficient for the entire application.
# A singleton object must satisfy two attributes
- Exactly one (well actually, at most one) instance of the object should exist.
- Everyone must be able to access that one singleton object. (This means that the object needs to be globally accessible.)
# code
public class Singleton {
private static Singleton singleton;
private Singleton() {}
public static synchronized Singleton getInstance() {
if (singleton == null) {
singleton = new Singleton();
}
return singleton;
}
}
# Singleton - another ver.
public class Singleton {
// volatile is 'synchronized' on the variable itself
private volatile static Singleton singleton = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return singleton;
}
}
# Declaring a volatile Java variable means: The value of this variable will never be cached thread-locally: all reads and writes will go straight to "main memory"; Access to the variable acts as though it is enclosed in a synchronized block, synchronized on itself.
댓글 영역