Singleton Explained

There are handful of ways to define a Singleton class in Java. They aren’t that difficult yet, doing it the correct way matters. Here I have listed 3 ways of doing it. However, only the 3rd which uses on-demand holder acronym is preferred as the singleton instance created here is thread-safe & is unique.

Trivia 1: Why we don’t import classes like System, Integer and String?
Ans: The package java.lang.*; is implicitly imported.

Trivia 2: Can main method of a java program reside in an abstract class?
Ans: Yes it can! See the Driver class below.

1. Eager Singleton

package design.com.hamzeen;

public class EagerSingleton {
	private static EagerSingleton ins = new EagerSingleton();

	public static EagerSingleton getInstance() {
		return ins;
	}

	private EagerSingleton() {
	}
}

2. Lazy Singleton

package design.com.hamzeen;

public class LazySingleton {
	private static LazySingleton ins;

	public static LazySingleton getInstance() {
		if (ins == null) {
			ins = new LazySingleton();
		}
		return ins;
	}

	private LazySingleton() {
	}
}

3. Singleton Holder

package design.com.hamzeen;

public class SingletonHolder {
	public static SingletonHolder getInstance() {
		return Holder.ins;
	}

	private static final class Holder {
	  private static final SingletonHolder ins = 
				new SingletonHolder();
	}

	private SingletonHolder() {
	}
}

The Driver and Output

package design.com.hamzeen;

public abstract class Driver {

	public static void main(String[] args) {
	  EagerSingleton a1 = EagerSingleton.getInstance();
	  EagerSingleton a2 = EagerSingleton.getInstance();
	  System.out.println(a1.toString());
	  System.out.println(a2.toString());

	  LazySingleton b1 = LazySingleton.getInstance();
	  LazySingleton b2 = LazySingleton.getInstance();
	  System.out.println(b1.toString());
	  System.out.println(b2.toString());

	  SingletonHolder c1 = SingletonHolder.getInstance();
	  SingletonHolder c2 = SingletonHolder.getInstance();
	  System.out.println(c1.toString());
	  System.out.println(c2.toString());
	}
}

design.com.hamzeen.EagerSingleton@15db9742
design.com.hamzeen.EagerSingleton@15db9742
design.com.hamzeen.LazySingleton@6d06d69c
design.com.hamzeen.LazySingleton@6d06d69c
design.com.hamzeen.SingletonHolder@7852e922
design.com.hamzeen.SingletonHolder@7852e922
Advertisements