static class vs singleton class

后端 未结 4 1971
猫巷女王i
猫巷女王i 2021-01-03 04:31

I know this topic has been discussed and killed over and over again, but I still had one doubt which I was hoping someone could help me with or guide me to a pre-existing po

4条回答
  •  迷失自我
    2021-01-03 04:48

    Singleton class is essentially a regular top-level class with a private constructor, to guarantee its singleness. Singleton class itself provides a way to grab its instance. Singleton classes are not very easy to test, therefore we tend to stick with the idea of Just Create Once.

    static class is essentially a nested class. A nested class is essentially a outer level class which is nested in another class just for packaging convenience. A top-level class can not be declared as static, in Java at least -- you should try it yourself.

    would this be dis-advantage for static classes when compared to singleton class?

    Your this question became somewhat invalid now, according to the above explanation. Furthermore, a static class (of course nested) can also be a singleton.

    Further reading:

    • Inner class in interface vs in class

提交回复
热议问题