Java中的Singleton模式和静态类的区别是什么?[英] What is the difference between a Singleton pattern and a static class in Java?






  • 可以扩展非静态类.多态性可以节省很多重复.
  • 非静态类可以实现接口,当您想将实现与API分开时,该接口可能会派上用场.


但是,单身模式距离静态类仅半步.您的有点获得这些好处,但是如果您通过" className.Incance"直接在其他类中访问它们,则您将创建访问这些好处的障碍.就像PH0ENIX指出的那样,使用依赖注入模式,您会更好.这样,可以告诉一个特定类是(或不是)单身人士的di框架.您将获得嘲笑,单位测试,多态性和更加灵活性的所有好处.




  • 可以扩展单身人士.静态不.
  • 单例创建如果未正确实现,则可能不会是线程安全.静态不.
  • 单身人士可以作为对象传递.静态不.
  • 单身人士可以收集垃圾.静态不.
  • 单身人比静态类好!
  • 更多这里,但我还没有意识到:)






How is a singleton different from a class filled with only static fields?


Almost every time I write a static class, I end up wishing I had implemented it as a non-static class. Consider:

  • A non-static class can be extended. Polymorphism can save a lot of repetition.
  • A non-static class can implement an interface, which can come in handy when you want to separate implementation from API.

Because of these two points, non-static classes make it possible to write more reliable unit tests for items that depend on them, among other things.

A singleton pattern is only a half-step away from static classes, however. You sort of get these benefits, but if you are accessing them directly within other classes via `ClassName.Instance', you're creating an obstacle to accessing these benefits. Like ph0enix pointed out, you're much better off using a dependency injection pattern. That way, a DI framework can be told that a particular class is (or is not) a singleton. You get all the benefits of mocking, unit testing, polymorphism, and a lot more flexibility.


Let's me sum up :)

The essential difference is: The existence form of a singleton is an object, static is not. This conduced the following things:

  • Singleton can be extended. Static not.
  • Singleton creation may not be threadsafe if it isn't implemented properly. Static not.
  • Singleton can be passed around as an object. Static not.
  • Singleton can be garbage collected. Static not.
  • Singleton is better than static class!
  • More here but I haven't realized yet :)

Last but not least, whenever you are going to implement a singleton, please consider to redesign your idea for not using this God object (believe me, you will tend to put all the "interesting" stuffs to this class) and use a normal class named "Context" or something like that instead.


A singleton can be initialized lazily, for one.