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

查看:23
本文介绍了Java 中的单例模式和静态类有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

单例与仅填充静态字段的类有何不同?

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:

  • 可以扩展非静态类.多态可以节省大量重复.
  • 非静态类可以实现接口,这在您想将实现与 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.

然而,单例模式离静态类只有半步之遥.您某种程度上获得了这些好处,但是如果您通过`ClassName.Instance'直接在其他类中访问它们,那么您就为访问这些好处设置了障碍.就像 ph0enix 指出的那样,您最好使用依赖注入模式.这样,可以告诉 DI 框架某个特定类是(或不是)单例.您可以获得模拟、单元测试、多态性和更多灵活性的所有好处.

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.

这篇关于Java 中的单例模式和静态类有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆