Answer Posted / dara
Ensure a class has only one instance, and provide a global
point of access to it. Singletons maintain a static
reference to the sole singleton instance and return a
reference to that instance from a static instance() method.
Example:
========
public class MyClassSingleton {
private static MyClassSingleton instance;
//Constructor must be protected or private to perevent
creating new object
protected MyClassSingleton() {
}
//could be synchronized
public static MyClassSingletongetInstance() {
if (instance==null)
instance = new MyClassSingleton()
return instance;
}
public void method1(){
System.out.println("hello singleton");
}
}//end of class
| Is This Answer Correct ? | 1 Yes | 1 No |
Post New Answer View All Answers
Can you start a thread twice in Java?
What is the purpose of interface?
What class allows you to read objects directly from a stream?
Can we declare a class as static?
What is the difference between an object-oriented programming language and object-based programming language?
What is nan in java?
What is a modifier?
Can we have more than one package statement in the source file?
Differences between C and Java?
Are arrays static in java?
What is the return type of the main method?
What are JVM.JRE, J2EE, JNI?
Does java support function overloading, pointers, structures, unions or linked lists?
Is empty list java?
What is the difference between a method and a procedure?