Collaboratione Software

Maintaining Global Objects Using Singleton

While developing object oriented software applications in almost every language there is a need of maintaining global objects, sometimes to maintain the application configurations or database connections. In the paradigm of OOP, software developers normally pass objects reference to the other classes through arguments using method calls. There is a simple yet powerful technique of maintaining global objects by using “singleton” concept.

Singleton is a simple class with private constructor, its own static object (As its constructor is private the object can only declare inside the body of the class, that the reason the class is the custodian of its object in singleton) and a static method to get the object instance (or sometimes a static property for particular languages). The class structure is a follows:

// A Database Connection Singletonclass DBConnection

{

//Static Database connection object

private static DBConnection myConnection = null;

//Private Class Constructor

private DBConnection()
{
}

//Static method to get the object

public static DBConnection GetDBConnection()

{
if (myConnection == null)
myConnection = new DBConnection();
return myConnection;
}

//Static property to get the oject instance

public static DBConnection myProperty

{
get
{
if (myConnection == null)
myConnection = new DBConnection();
return myConnection;
}
}

//Other method calls

public void InitiateConnection()
{
Console.WriteLine(“Initiate Method Call”);
}
}

Singleton are easy to use yet not violating the object oriented programming rules. It can be implemented in any object oriented supporting language. It can be thread safe in case of multithreaded environment by simply adding a mutex lock while instantiating the class object.