Implementing the singleton pattern in Java

前端 未结 6 751
一生所求
一生所求 2020-11-30 06:09

Can anyone provide an example of a singleton pattern and explain why they are necessary?

6条回答
  •  误落风尘
    2020-11-30 06:56

    Basically, in Java you implement singleton by giving a class a private no-args constructor (private MyClass()), and statically (or lazily) initializing a single instance of the class which is returned by a static MyClass getInstance() method.

    You would use this when you want there to be no more than a single instance of your class throughout the entire application.

提交回复
热议问题