How to create a singleton class

前端 未结 7 1046
粉色の甜心
粉色の甜心 2020-12-02 13:10

What is the best/correct way to create a singleton class in java?

One of the implementation I found is using a private constructor and a getInstance() method.

<
7条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-02 13:54

    If you are using reflection to pierce encapsulation, you should not be surprised when behavior of your class is altered in incorrect ways. Private members are supposed to be private to the class. By using reflection to access them you are intentionally breaking the behavior of the class, and the resultant "duplicate singleton" is expected.

    In short: Don't do that.

    Also, you might consider creating the singleton instance in a static constructor. Static constructors are synchronized and will only run once. Your current class contains a race condition -- if two separate threads call getInstance() when it has not been previously called, there is a possibility that two instances will be created, one of them being exclusive to one of the threads, and the other becoming the instance that future getInstance() calls will return.

提交回复
热议问题