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

前端 未结 10 1118
心在旅途
心在旅途 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:50

    For singletons and utilty classes you can use an enum which is a final class and implicitly defines a private constructor.

    enum Singleton {
         INSTANCE
    }
    

    or

    enum Utility {;
    
    }
    

    In your example above you have a utility class because you have no instance fields, methods and don't create an instance.

    0 讨论(0)
  • 2020-12-10 08:54

    If there no such a private constructor, Java will provide a default public one for you. Then you are able to call this constructor multiple times to create several instances. Then it is not a singleton class any more.

    0 讨论(0)
  • 2020-12-10 08:57

    If you don't need lazy initiation:

    public class Singleton {
        private static final Singleton instance = new Singleton();
    
        // Private constructor prevents instantiation from other classes
        private Singleton() { }
    
        public static Singleton getInstance() {
                return instance;
        }
    }
    

    is the best way, because is thread safe.

    0 讨论(0)
  • 2020-12-10 08:58

    For the singleton pattern you use an private constructor to ensure that no other instances can be created, otherwise it wouldn't be a singleton.

    0 讨论(0)
提交回复
热议问题