Java Singleton Pattern

Sort by

recency

|

164 Discussions

|

  • + 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();
    }
    

    }

  • + 0 comments
    class Singleton{
        private Singleton() {}
        
        public String str;
        
        public static Singleton getSingleInstance() {
            return new Singleton();
        }
    }