Tuesday, May 25, 2010

The Singleton Pattern

Perhaps the most simplest pattern of all is the ubiquitous Singleton pattern. This pattern is used in an application where no more than one instance of the class is allowed/desired. For example, a database connection can be only one for a application; No more than a single printer object can exist for an application; A application wide object.

How do we make a class return no more than one instance? One way is to make the constructor private. This makes sure no object of this class can be created outside of the class. We then add a static method which creates the object of the class, if it does not exist already, and return it to the caller.

Following code outlines our process:

public class DBConnection
{

private static DBConnection dbConnection;


private DBConnection()

{
/* Create connection here using the various DB parameters*/
}
public static DBConnection getInstance()
{
if(dbConnection == null)
{
dbConnection = new DBConnection();
}
return dbConnection;
}
/*Add other required methods*/
}

No comments:

Post a Comment