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

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

问题描述

解决方案

几乎每次我写一个静态类时我最终希望我把它实现为一个非静态类。考虑:




  • 可以扩展非静态类。多态可以节省大量的重复。

  • 非静态类可以实现一个接口,当你想从API中分离实现时,这个接口可以派上用场。



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

然而,单例模式距离静态类只有一步之遥。您 可以获得这些好处,但如果您通过ClassName.Instance在其他类中直接访问它们,那么您在创建访问这些优势的障碍。像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.

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

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