Singleton Pattern – Design Patterns in Java

The Singleton Pattern Ensure a class only has one instance, and provide a global point of access to it.For example ,if we need a connection to single database at one time  or when ever we are referring to to single application.properties file in struts application for showing application in one language at one time.Then we can need of singleton pattern or you can use it to create a connection pool. It’s not wise to create a new connection every time a program needs to write something to a database; instead, a connection or a set of connections that are already a pool can be instantiated using the Singleton pattern.

Need of Singleton Pattern

– Sometimes we want just a single instance of a class to exist in the system

– We need to have that one instance easily accessible

– And we want to ensure that additional instances of the class can not be created

Benefits of Pattern

– Controlled access to sole instance

– Permits a variable number of instances

How we can Implement singleton pattern

We will be using statis method to call the client to get a reference to the

single instance and we’ll use a private constructor

/* SingletonHolder is loaded on the first execution of Singleton.getInstance()
* or the first access to SingletonHolder.INSTANCE, not before.
*/

public class VinaySingleton {

private static VinaySingleton  VINAYINSTANCE ;

private VinaySingleton() {
}

public static VinaySingleton  getInstance() {
if(VINAYINSTANCE ==null){
VINAYINSTANCE = new VinaySingleton();
}

return VINAYINSTANCE;

}

We will be having private constructor which tells that no other outside classes can directly instantiate this class. The only way to get a reference to the VinaySingleton object is to make a call to the static method VinaySingleton.getInstance ().Similarly create Myconnection class and method as above


Even if client call the VinaySingleton.getInstance multiple time the multiple object will point to same reference.

package techartifact.pattern.singleton;
public class VinayClient {
public static void main(String[] args) {

 VinaySingleton i1 = VinaySingleton.getInstance();
 MyConnection i2 = MyConnection.getInstance();

 if (i1 == i2){
System.out.println("Both the object pointing to same reference");
 }else{
System.out.println("Objects are not equal");
}
 }
}

Vinay

I am an Oracle ACE in Oracle ADF/Webcenter. Sr Java Consultant-working on Java/J2EE/Oracle ADF/Webcenter Portal/ content and Hibernate for several years. I'm an active member of the OTN JDeveloper/Webcenter forum. Passionate about learning new technologies. I am here to share my knowledge. Give your views and suggestion on [email protected] .

More Posts - Website

Follow Me:
TwitterLinkedInGoogle PlusYouTube