• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

singleton class or to have a static variable in a class

 
anil bisht
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Regarding having a singleton class and having a static object in the class, which is the better way to implement.
See i need to get the reference data from the database and store them in the hashtable. So whenever some method needs the data it will call that class and and if hashtable in not empty it will get the data from the database else get from the hashtable.
now i have two options
1) to have a class having a static hashtabe
The code goes like this..
public class refdata {
private static Hashtable data = new Hashtable();
public static synchronized String getvalue(String strKey) {
String value = data.get(strKey)
if(value == null) {
// get the details from the databese and populate the hashtable
String value = data.get(strKey)
}
return value
}
}
here i can directly write refdata.getvalue("test")

2)
To have a static class inside the class and have a private hashtable
public class CDBDQReferenceData
{
static private CDBDQReferenceData objReferenceData; //Singleton instance
static private HashMap hmpOutputCodeDetails; // the output HashMap of Code Details
private CDBDQReferenceData()
{
//code to put get the data from teh hashtable and put it into the hashtable
}
public static CDBDQReferenceData getReferenceData()
{
if (objReferenceData == null)
{
objReferenceData = new CDBDQReferenceData();
}
return objReferenceData;
}
public string getValue(String strkey)
{
String value = hmpOutputCodeDetails.get(strKey)
}
}
in this case i will get an object of this class and then i can call the get value to get the dateils
here i need to write
CDBDQReferenceData.getReferenceData().getValue("test");
what are the merits and demerits of using a singleton instance ??
Which method can be better ??
TIA
Anil
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic