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

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

    A static class is different from a singleton in that a a singleton class enforces that there is always at most one instance. A static class has no instances, and is just a bundle of static functions and static data.

    So for a Singleton class, i.e. one with at most one instance, then a private constructor is required.

    In your example, it looks like the Singleton class fits more than the static class- because of the connection and dataSource members. Make those members private, your constructor private and provide static methods that reference a static ConnPoolFactory instance. If instance is null, create a new one, otherwise just use it.

提交回复
热议问题