Why is it mandatory to have private Constructor inside a Singleton class

前端 未结 10 1132
心在旅途
心在旅途 2020-12-10 08:12

This is my singleton class for obtaining the database connection.

I have a question here: why it compulsory to have a private constructor inside a singleton class (a

10条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-10 08:39

    Singleton def:

    Ensure the only one object need to create for the entire main stack (per main class).

    If you want to satisfy above statement then we should give constructor as a private. Actually through singleton we are getting ref not object that's why it is not mandatory then we can create object in other classes but we can't access reference (Constructor as public).

    Ex:

    public class SingleTon {
    
        private static SingleTon s;
        public SingleTon() {}
    
        public static SingleTon getInstance() {
            if (s == null) {
                s = new SingleTon();
                System.out.println("ho ho");
            } else{
                return s;
            }
            return s;
        }
    }
    

    Other class:

    public class Demo {
    
        public static void main(String[] args) {
            //SingleTon s=SingleTon.getInstance();
    
            SingleTon s11=new SingleTon();
            SingleTon s12=new SingleTon();
            s11.getInstance();
            s12.getInstance();
        }
    }
    

    Output:

    ho ho
    

提交回复
热议问题