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

本文是小编为大家收集整理的关于Java中的Singleton模式和静态类的区别是什么?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

单身人士与仅装有静态字段的课程有何不同?

推荐答案

几乎每次写静态类时,我都希望我将其作为非静态类实现.考虑:

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

由于这两个点,非静态类使得可以为依赖于它们的项目编写更可靠的单元测试.

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

其他推荐答案

让我总结一下:)

本质上的区别是:单例的存在形式是一个对象,静态不是.这揭示了以下内容:

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

最后但并非最不重要的一点是,每当您要实施单身人士时,请考虑重新设计您的想法不使用这个神对象(相信我,您倾向于将所有"有趣"的东西放入此类中)并使用一个名为"上下文"或类似的普通类.

其他推荐答案

可以懒洋洋地初始化单身人士.

本文地址:https://www.itbaoku.cn/post/627560.html

问题描述

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.