How to implement Singleton

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


Please Help Members By Posting Answers For Below Questions

Which is bigger double or float?

629


When do we need to use internal iteration? When do we need to use external iteration?

697


How many types of string data types are there?

636


what is the constructor and how many types of constructors are used in java?

618


What is static variable with example?

658






What is mnemonic in assembly language?

659


What is nested class?

646


What is a singleton puppy?

625


What is difference between java and java ee?

653


Why does the integer quotient -0/3 yield 0, but the double quotient -0.0/3.0 yields – 0.0?

719


What advantage do java's layout managers provide over traditional windowing systems?

633


Does google use java?

631


Why is multithreading important?

580


What do you understand by an io stream?

691


How does compareto method work?

613