File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: singleton class or to have a static variable in a class
 
Similar Threads
singleton class or to ahve a static variable inside a class
jComboBox
General Application Help
Singleton Pattern Question
Multi-threads access singleton