This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Beginning Java and the fly likes singleton class or to  have a static variable in a class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "singleton class or to  have a static variable in a class" Watch "singleton class or to  have a static variable in a class" New topic
Author

singleton class or to have a static variable in a class

anil bisht
Ranch Hand

Joined: Nov 04, 2000
Posts: 81
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
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: singleton class or to have a static variable in a class