Categories:
.NET (357)
C (330)
C++ (183)
CSS (84)
DBA (2)
General (7)
HTML (4)
Java (574)
JavaScript (106)
JSP (66)
Oracle (114)
Perl (46)
Perl (1)
PHP (1)
PL/SQL (1)
RSS (51)
Software QA (13)
SQL Server (1)
Windows (1)
XHTML (173)
Other Resources:
How can we make a class Singleton
How can we make a class Singleton
✍: Guest
A) If the class is Serializable
class Singleton implements Serializable
{
private static Singleton instance;
private Singleton() { }
public static synchronized Singleton getInstance()
{
if (instance == null)
instance = new Singleton();
return instance;
}
/**
If the singleton implements Serializable, then this
* method must be supplied.
*/
protected Object readResolve() {
return instance;
}
/**
This method avoids the object fro being cloned
*/
public Object clone() {
throws CloneNotSupportedException ;
//return instance;
}
}
B) If the class is NOT Serializable
class Singleton
{
private static Singleton instance;
private Singleton() { }
public static synchronized Singleton getInstance()
{
if (instance == null)
instance = new Singleton();
return instance;
}
/**
This method avoids the object from being cloned
**/
public Object clone() {
throws CloneNotSupportedException ;
//return instance;
}
}
2013-03-18, 2197👍, 0💬
Popular Posts:
1. What is normalization. 2. Difference between procedure and functions. 3. Oracle 9i Vs 10g. 4. how...
How to make elements invisible? Change the "visibility" attribute of the style object associated wit...
.NET INTERVIEW QUESTIONS - What are Daemon threads and how can a thread be created as Daemon? Daemon...
What are the types of variables x, y, y and u defined in the following code? #define Atype int* type...
Wha is the output from System.out.println("Hell o"+null);?Hellonull