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

In java, how many ways you can take input from the console?

524


What is the difference between Error, defect,fault, failure and mistake?

662


When should a function throw an exception?

599


How to create packages in java?

533


What is an eror in java?

559






Is empty string in java?

544


What is a java string?

544


Can we overload the constructors?

561


Can a java program have 2 main methods?

550


What is the static keyword?

592


What are exceptions

644


Tell me how many ways are there to initialise an integer with a constant.

647


What state does a thread enter when it terminates its processing in java programming?

578


Can we override tostring method in java?

533


what is difference between equals and ==?

591