Archive

Archive for November, 2015

Singleton Pattern

November 15, 2015 Leave a comment

Singleton pattern restrict that only one instance of the class exists in the java virtual machine.  There are several approach to implement singleton pattern but all of them have same common step.

  • Private constructor to restrict instantiation of the class from outside
  • Private static variable of the same class
  • Public method that returns the instance of the class
singleton design pattern

Singleton Pattern

  • Eager Init

In eager init, instance of class is created at the time of class loading even is not needed yet.

public class EagerInit {
	private static volatile EagerInit instance = new EagerInit();

	private EagerInit() {
	}

	public static EagerInit getInstance() {
		return instance;
	}
}
  • Static Block Init

Static block init is similar with eager init.

public class StaticBlockInit {
	private static StaticBlockInit instance;

	private StaticBlockInit() {
	}

	static {
		try {
			instance = new StaticBlockInit();
		} catch (Exception ex) {
			throw new RuntimeException("Exception occured in creating singleton instance");
		}
	}

	public StaticBlockInit getInstance() {
		return instance;
	}
}
  • Lazy Init

In lazy init, instance is created in global access method.

public class LazyInit {
	private static LazyInit instance;

	private LazyInit() {
	}

	public static LazyInit getInstance() {
		if (instance == null) {
			synchronized(LazyInit.class){
				if(instance == null){
					instance = new LazyInit();
				}
			}
		}
		return instance;
	}
}
Advertisements