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

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

    There is a school of thought that considers the Singleton pattern to in fact be an anti-pattern.

    Considering a class A that you only wish to have one of, then an alternative is to have a builder or factory class that itself limits the creation of the number of objects of Class A, and that could be by a simple counter. The advantage is that Class A no longer needs to worry about that, it concentrates on its real purpose. Every class that uses it no longer has to worry about it being a singleton either (no more getInstance() calls).

提交回复
热议问题