Singleton Pattern

 

Singleton is the simplest of all patterns.

 

When to use: - Use it when you want to make sure that only one instance of a class is created at any point of time in an application and all other objects share this single instance.

 

Example: - JDBC Connection Pool in a web application.

 

There are three ways to create a singleton class. Select the suitable one depending upon your need.

 

Type -1

 

When to use

 

Advantage

 

Disadvantage

 

public class ConnectionPool {

 

// step1 :- Declare a private static instance variable and initialize it.

private static _poolInstance = new ConnectionPool();

// step 2 :- Make the constructor private.

private ConnectionPool() {

}

 

// step 3 :- Provide a static method to get the shared instance.

public static ConnectionPool getInstance() {

return _poolInstance;

}

}

 

Type -2

 

public class ConnectionPool {

 

// step1 :- Declare a private static instance variable.

private static _poolInstance = null;

// step 2 :- Make the constructor private.

private ConnectionPool() {

}

 

// step 3 :- Provide a static method to get the shared instance.

public static synchronsized ConnectionPool getInstance() {

if (_poolInstance == null)

_poolInstance = new ConnectionPool();

return _poolInstance;

}

}

 

Type -3

 

public class ConnectionPool {

 

// step 1 :- Declare a private static volatile instance variable.

private static volatile _poolInstance = null;

// step 2 :- Make the constructor private.

private ConnectionPool() {

}

 

// step 3 :- Provide a static method to get the shared instance.

public static ConnectionPool getInstance() {

if (_poolInstance == null) {

synchronized(this) {

if (_poolInstance == null) {

_poolInstance = new ConnectionPool();

}

}

return _poolInstance;

}

}