Skip to content

Instantly share code, notes, and snippets.

@WaltXin
Last active June 28, 2018 20:12
Show Gist options
  • Save WaltXin/9e7b76cd704bdff3d9a51be26b3f79d1 to your computer and use it in GitHub Desktop.
Save WaltXin/9e7b76cd704bdff3d9a51be26b3f79d1 to your computer and use it in GitHub Desktop.
Design Pattern

Design Pattern

Observer

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 Observer

Singleton

Restrict the instantiation of a class to one object. eg:Login system.
Singleton

1.Eager Initialization

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;
	}
}
2.Lazy Initialization

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;
	}
}
3.Enum Initialization

Enum is also thread safe and very efficient, recommend.

public enum SingletonEnum {
	instance;
	public void method() {
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment