Home > Java > Singleton Pattern

Singleton Pattern

November 15, 2015 Leave a comment Go to comments

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
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: