Saturday, February 25, 2012

Java Design Pattern - Singleton

Usage:

This pattern apply where application need only one instance for a particular class.

Purpose of this pattern make sure that only one object of the class is created for entire application and that object is shared across multiple modules/clients of single application.

It allow global point of access to that single instance

Example scenarios:

1.Database connection for a particular session
2.Single object for referencing Global properties

JAVA Example:

package com.pattern.singleton;

public class DBConnection {

private static DBConnection connection;

private DBConnection() {}

public static DBConnection getConnection() {

    if(connection == null) {
        synchronized (DBConnection.class) {
            if (connection == null) {
                connection = new DBConnection();
            }
       }
    }
    return connection;
}

}

We should careful while creating singleton on multiple threads application.

If we don't synchronize the method which is going to return the instance then, there is a possibility of creating multiple instances in a multi-threaded scenario. This example is threadsafe singleton pattern.

No comments:

Post a Comment