An application calls an Observable object's notifyObservers method to have all the object's observers notified of the change.
Usage: Weather notification, wechat notification
Restrict the instantiation of a class to one object. eg:Login system.
The instance of Singleton class is created at the time of class loading
Drawback: Instance is created even though client application might not be using it
public class Singleton {
private static Singleton instance = new Singleton();
public static Singleton getInstance() {
return instance;
}
}Lazy initialization solve the eager's issues, in order to make sure the thread safe, use synchronized and double check here.
public class SingletonLazy {
//volatile is optional, volatile make sure the variable get value from RAM(hint: JMM)
private static volatile SingletonLazy instance = null;
public static SingletonLazy getInstance() {
if (instance == null) {
synchronized(SingletonLazy.class) {
if (instance == null) {
instance = new SingletonLazy();
}
}
}
return instance;
}
}Enum is also thread safe and very efficient, recommend.
public enum SingletonEnum {
instance;
public void method() {
}
}
