Singleton design pattern

Singleton design pattern:

This is the simplest and most useful design pattern in java. Singleton design comes under creational pattern as this pattern provides one of the best ways to create an object. This pattern involves a single class which is responsible to create an object while making sure that only single object gets created.

Singleton Pattern in one sentence is “define a class that has only one instance and provides a global point of access to it”.

There are two forms or way of creating singleton design pattern.

  1. Early Instantiation à Class load time
  2. Lazy Instantiation à when required create object.

Singleton pattern is mostly used in multi-threaded and database applications. It is used in logging, caching, thread pools, configuration settings etc.

A singleton is a class instantiated only once. We can achieve this by creating static field in a class representing the class. A static method exists in a class which returns object of that class.

How to achieve early instantiation?

Example code:

package basicsingleton;

public class Singleton {

private static Singleton obj = new Singleton();

private Singleton() {

}

public static Singleton getInstance() {

return obj;

}

}

How to achieve lazy instantiation?

Example code:

package basicsingleton;

public class Singleton {

private static Singleton obj = null;

private Singleton() {

}

public static synchronized Singleton getInstance() {

if (null == obj) {

obj = new Singleton();

}

return obj;

}

}

}

java

No Responses

Leave a Reply

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