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

What is the final class modifier?

555


Why do we need wrapper class?

535


Do you know how to reverse string in java?

582


Explain the difference between treeset and treemap in java?

525


What is the java idl system?

581






Explain the scope of a variable.

627


How many types of operators are there?

519


What is a “stateless” protocol ?

551


What is scope & storage allocation of static, local and register variables? Explain with an example.

562


Why we use methods in java?

534


What classes of exceptions may be thrown by a throw statement?

524


What is immutable in java?

539


What is number data type?

530


Can we call virtual funciton in a constructor ?

1770


What are unchecked exceptions in java?

610