Singleton pattern is evil!

Posted on Wednesday, October 20, 2010 by Anuj Mehta

Singleton pattern is one of the most commonly used patterns. Though it has benefits of its own but there are some inherent problems associated with this pattern which I had observed in my recent work.

Scenario1:
Consider following dummy example where we have a class “Dummy”


public class Dummy {

private static Dummy dummyObject;
private List m_dataList;

private Dummy()
{
m_dataList = new ArrayList();
}

public static Dummy getInstance()
{
if(dummyObject == null)
dummyObject = new Dummy();
return dummyObject;
}

public void saveData(String data)
{
m_dataList.add(data);
}

public List getData()
{
return new ArrayList(m_dataList);
}
}


Now we will be using this class like this


Dummy dummyObj = Dummy.getInstance();
dummyObject.saveData("some data");


Now consider a scenario where we use object of this class in 2-3 classes for some specific operation only but since we have “static” reference to Dummy object it won’t ever be removed from memory till the lifetime of the product i.e. now we have resident in memory an object of Dummy class which is not frequently used. This makes a clear case of memory leak.

Proposed resolution
We can provide a method for doing a clean-up i.e. releasing all the resources that this object uses. Onus of doing cleanup lies with the user of this class as only that class knows when it is done with this class.


Scenario2:
Consider a dummy class “InitManager” which is one of the many manager classes that are invoked at the starting of let’s say client or server.


public class InitManager
{
private static InitManager initMgr;

private InitManager()
{

}

public static InitManager getInstance()
{
if(initMgr == null)
initMgr = new InitManager();
return initMgr;
}

/**
* This method performs some boilerplate
* tasks.
*/
public void performTask()
{
//do the initialization task
}
}


Now let’s suppose that this class is used only during initialization after which it’s not used throughout the execution of the product i.e. we do something like
InitManager initMgrObject = InitManager.getInstance();
initMgrObject.performTask();

Now the object of InitManager will remain in memory during the lifetime of the product as it has “static” reference which will be released only when the application stops execution. This is clear case of memory leak. A better and simpler approach for this is to have static methods and there is no need to create objects in such cases.


public class InitManager
{
public InitManager()
{

}

/**
* This method performs some boilerplate
* tasks.
*/
public static void performTask()
{
//do the initialization task
}
}

0 Responses to "Singleton pattern is evil!":