Java Singleton Pattern

Sort by

recency

|

165 Discussions

|

  • + 0 comments
    import java.util.*;
    import java.text.*;
    import java.math.*;
    import java.util.regex.*;
    import java.lang.reflect.*;
    
    
    class Singleton{
         private static Singleton obj;
         public String str;
         private Singleton()
         {
             
         }
        public static Singleton getSingleInstance()
        {
            if(obj==null)
            {
                        obj=new Singleton();   
            }
            return obj;
        }
    }
    
  • + 0 comments
    class Singleton{
        private static Singleton instance = null;
        private Singleton(){};
        public String str;
        public static Singleton getSingleInstance(){
            if (instance == null){
                instance = new Singleton();
                return instance;
            }
            return instance;
        }
    }
    
  • + 0 comments

    Hmmm... Using Holder pattern to solve this challenge will fail.

  • + 0 comments

    class Singleton{

    private static Singleton instance;
    public String str;
    
    private Singleton() {
    }
    
    public static Singleton getSingleInstance() {
        if(instance == null) {
            synchronized(Singleton.class) {
                if(instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
    

    }

  • + 0 comments

    class Singleton{

    public String str;
    
    private Singleton()
    {
    }
    public static Singleton getSingleInstance()
    {
        return new Singleton();
    }
    

    }