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

后端 未结 9 1540
离开以前
离开以前 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:25

    You want the Singleton pattern. There is an excellent discussion of how to implement this properly. If you do this right, there will only ever be one instance of the class.

    Essentially what you are going to do is create a class, hold a single instantiated object of that class at the static level, and provide a static accessor to get it (getInstance() or similar). Make the constructor final so people can't create their own instances out of the blue. That link above has plenty of great advice on how to do this.

提交回复
热议问题