How to write a Singleton in proper manner?

后端 未结 13 1132
走了就别回头了
走了就别回头了 2020-12-23 12:03

Today in my interview one interviewer asked me to write a Singleton class. And i gave my answer as

public class Singleton {

    private static Singleton re         


        
13条回答
  •  盖世英雄少女心
    2020-12-23 12:52

    Why can't you do just

    public class SingletonSandBox {
    
        private static SingletonSandBox instance = new SingletonSandBox();
    
        private SingletonSandBox(){
        }
    
        public static SingletonSandBox getInstance(){
            return instance;
        }
    
    }
    

    and test

    public static void main(String[] args) {
    
            SingletonSandBox sss1 = SingletonSandBox.getInstance();
    
            SingletonSandBox sss2 = SingletonSandBox.getInstance();
    
            System.out.println(sss1 == sss2);
    
    }
    

    As I know this is thread-safe and shorter than using static block. Again static field declaration is read earlier comparing to static block by the runtime.

提交回复
热议问题