Singleton class:::Nucleous Software Java Interview Questions: Qu7
What is Singleton Class: How will you make a class singloton....
----------------------------------------------------------------------Singleton class:
This is a class which can be instatiated only once.
Eg:
Public class Singleton
{
private static single = new Singleton();
Private Singleton();
{}
}
For a singleton class, the constructor is made private and
a static variable is used for instatiating the class.
Public class Singleton
ReplyDelete{
private static single = new Singleton();
private Singleton() {}
public static Singleton getInstance( ) {
return singleton;
}
}
Only one thread access at a time
ReplyDelete-------------------------------------------------------------------------------------
class Singleton{
private static Singleton instance;
private Singleton() {
System.out.println("Hello....");
}
public static synchronized Singleton getInstance( ) {
if(instance == null) {
instance = new Singleton();
}
return instance;
}
}
public class Test {
public static void main(String [] args){
Singleton s=Singleton.getInstance();
}
}
You can use static inner class...
ReplyDelete------------------------------------------------
class Singleton {
private static class Loader {
static Singleton INSTANCE = new Singleton();
}
private Singleton () {
System.out.println("hello");
}
public static Singleton getInstance() {
return Loader.INSTANCE;
}
}
For multithread environment if you need to gurantee that all threads are accessing a single instance of a class:
ReplyDelete-------------------------------------------------
enum MySingleton {
SINGLE;
public void getInstance(){
System.out.println("Hello");
}
}
public class Test {
public static void main(String [] args){
MySingleton.SINGLE.getInstance();
}
}