How would You Implement Singleton Pattern?

The singleton pattern is one of the simplest design patterns. Sometimes we need to have only one instance of our class for example a single DB connection shared by multiple objects as creating a separate DB connection for every object may be costly. Similarly, there can be a single configuration manager or error manager in an application that handles all problems instead of creating multiple managers.

Definition:
The singleton pattern is a design pattern that restricts the instantiation of a class to one object.
Let’s see various design options for implementing such a class. If you have a good handle on static class variables and access modifiers this should not be a difficult task.

 

// Classical Java implementation of singleton 
// design pattern 
class Singleton 
{ 
	private static Singleton obj; 

	// private constructor to force use of 
	// getInstance() to create Singleton object 
	private Singleton() {} 

	public static Singleton getInstance() 
	{ 
		if (obj==null) 
			obj = new Singleton(); 
		return obj; 
	} 
} 

Leave a Reply

Your email address will not be published. Required fields are marked *