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

Is class is a data type?

583


What are the basics of core java?

558


Why do we create public static method in java?

595


What are the different types of inner classes?

536


What is an interface in java? Explain

589






What is the difference between C++ and Java and your preferences?

627


What is public static void main?

583


Can we execute a program without main() method?

539


Difference between object and reference?

694


What will happen if there is a default method conflict as mentioned above and we have specified the same signature method in the base class instead of overriding in the existing class ?

527


what is the role of xml in core java?? and how we can use it?? can somebody give a sample program with explanation and from where i can read more about xml?????

1814


Can extern variables be initialized?

518


Explain access specifiers?

663


What ide should I use for java?

504


How many bytes are there?

551