How to make sure that there is just one instance of class in JVM?

后端 未结 9 1614
离开以前
离开以前 2021-02-01 05:48

I am developing a design pattern, and I want to make sure that here is just one instance of a class in Java Virtual Machine, to funnel all requests for some resource through a s

9条回答
  •  灰色年华
    2021-02-01 06:36

    Use enum. In Java enum is the only true way to create a singleton. Private constructors can be still called through reflection.

    See this StackOverflow question for more details: Implementing Singleton with an Enum (in Java)

    Discussion: http://javarevisited.blogspot.com/2012/07/why-enum-singleton-are-better-in-java.html

提交回复
热议问题