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.
 
 

Comments

  1. Public class Singleton
    {
    private static single = new Singleton();

    private Singleton() {}

    public static Singleton getInstance( ) {
    return singleton;
    }
    }

    ReplyDelete
  2. Only one thread access at a time
    -------------------------------------------------------------------------------------
    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();


    }
    }

    ReplyDelete
  3. You can use static inner class...
    ------------------------------------------------
    class Singleton {

    private static class Loader {
    static Singleton INSTANCE = new Singleton();
    }

    private Singleton () {
    System.out.println("hello");
    }

    public static Singleton getInstance() {
    return Loader.INSTANCE;
    }
    }

    ReplyDelete
  4. For multithread environment if you need to gurantee that all threads are accessing a single instance of a class:
    -------------------------------------------------
    enum MySingleton {
    SINGLE;
    public void getInstance(){
    System.out.println("Hello");
    }
    }

    public class Test {

    public static void main(String [] args){

    MySingleton.SINGLE.getInstance();
    }
    }

    ReplyDelete

Post a Comment

Popular posts from this blog

Struts 2 : Warning :No configuration found for the specified action: 'Login.action' in namespace: '/'

Upload csv file at Google Cloud Storage using java

Read Images from a xlsx file using Apache POI