Resist the Temptation of the Singleton Pattern「建议收藏」

Resist the Temptation of the Singleton Pattern

大家好,又见面了,我是全栈君。

Resist the Temptation of the Singleton Pattern

Sam Saariste

THE SiNGLETON PATTERN SOLVES MANY OF YOUR PROBLEMS. You know that you only need a single instance. You have a guarantee that this instance is initialized before it’s used. It keeps your design simple by having a global access point. It’s all good. What’s not to like about this classic design pattern?

Quite a lot, it turns out. Tempting they may be, but experience shows that most singletons really do more harm than good. They hinder testability and harm maintainability. Unfortunately, this additional wisdom is not as widespread as it should be, and singletons continue to be irresistible to many programmers. But they are worth resisting:
• The single-instance requirement is often imagined. In many cases, it’s pure speculation that no additional instances will be needed in the future. Broadcasting such speculative properties across an application’s design is bound to cause pain at some point. Requirements will change. Good design embraces this. Singletons don’t.
• Singletons cause implicit dependencies between conceptually independent units of code. This is problematic both because they are hidden and because they introduce unnecessary coupling between units. This code smell becomes pungent when you try to write unit tests, which depend on loose coupling and the ability to selectively substitute a mock implementation for a real one. Singletons prevent such straightforward mocking.
• Singletons also carry implicit persistent state, which again hinders unit testing. Unit testing depends on tests being independent of one another, so the tests can be run in any order and the program can be set to a known state before the execution of every unit test. Once you have introduced singletons with mutable state, this may be hard to achieve. In addition, such globally accessible persistent state makes it harder to reason about the code, especially in a multithreaded environment.
146 97 Things Every Programmer Should Know

• Multithreading introduces further pitfalls to the singleton pattern. As straight- forward locking on access is not very efficient, the so-called double-checked locking pattern (DCLP) has gained in popularity. Unfortunately, this may be a further form of fatal attraction. It turns out that in many languages, DCLP is not thread-safe and, even where it is, there are still opportunities to get it subtly wrong.
The cleanup of singletons may present a final challenge:
• There is no support for explicitly killing singletons. This can be a serious issue in some contexts—for example, in a plug-in architecture where a plug-in can only be safely unloaded after all its objects have been cleaned up.
• There is no order to the implicit cleanup of singletons at program exit. This can be troublesome for applications that contain singletons with interdependencies. When shutting down such applications, one single- ton may access another that has already been destroyed.
Some of these shortcomings can be overcome by introducing additional mechanisms. However, this comes at the cost of additional complexity in code that could have been avoided by choosing an alternative design.
Therefore, restrict your use of the Singleton pattern to the classes that truly must never be instantiated more than once. Don’t use a singleton’s global access point from arbitrary code. Instead, direct access to the singleton should come from only a few well-defined places, from where it can be passed around via its interface to other code. This other code is unaware, and so does not depend on whether a singleton or any other kind of class implements the interface. This breaks the dependencies that prevented unit testing and improves the main- tainability. So, the next time you are thinking about implementing or accessing a singleton, I hope you’ll pause and think again.

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/116135.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • matlab求解不定方程组_matlab解参数方程组

    matlab求解不定方程组_matlab解参数方程组最想说的一句话:要查matlab用法,一定要到官网去查,一些用法matlab官方是在不断更新的,现存的一些办法已经无法解决问题使用的是solve这个函数它拥有解决优化问题,解方程的功能,下面我将举一些常用的例子文章目录一、解单变量方程二、解多变量方程三、解带参数方程四、解不等式知识点总结一、解单变量方程题目:求解方程2x+1=0 2x+1=02x+1=0symsx…

    2025年11月14日
    5
  • mysql datetime、date、time、timestamp区别

    mysql datetime、date、time、timestamp区别mysql datetime、date、time、timestamp区别

    2022年4月24日
    45
  • hashmap和hashtable和hashset的区别_java中hashcode和equals的区别

    hashmap和hashtable和hashset的区别_java中hashcode和equals的区别HashMap与HashTable的区别HashMap与Hashtable的区别是面试中经常遇到的一个问题。这个问题看似简单,但如果深究进去,也能了解到不少知识。本文对两者从来源,特性,算法等多个方面进行对比总结。力争多角度,全方位的展示二者的不同,做到此问题的终结版。1作者Hashtable的作者:HashMap的作者:HashMap的作者比Hashta…

    2022年9月18日
    2
  • ccproxy代理搭建_自动代理

    ccproxy代理搭建_自动代理由于公司内网windows系统要更新,特设置代理访问外网https://blog.csdn.net/cyl937/article/details/21330607

    2025年7月28日
    2
  • 常用的web漏洞扫描工具_十大常用管理工具

    常用的web漏洞扫描工具_十大常用管理工具Webscantool推荐10大Web漏洞扫描程序Nikto这是一个开源的Web服务器扫描程序,它可以对Web服务器的多种项目(包括3500个潜在的危险文件/CGI,以及超过900个服务器版本,还有250多个服务器上的版本特定问题)进行全面的测试。其扫描项目和插件经常更新并且可以自动更新(如果需要的话)。Nikto可以在尽可能短的周期内测试你的Web服务器,这在其日志文件中…

    2025年11月5日
    6
  • 7-10 公路村村通(并查集kruskal)

    7-10 公路村村通(并查集kruskal)最小生成树题目链接现有村落间道路的统计数据表中,列出了有可能建设成标准公路的若干条道路的成本,求使每个村落都有公路连通所需要的最低成本。输入格式:输入数据包括城镇数目正整数N(≤1000)和候选道路数目M(≤3N);随后的M行对应M条道路,每行给出3个正整数,分别是该条道路直接连通的两个城镇的编号以及该道路改建的预算成本。为简单起见,城镇从1到N编号。输出格式:输出村村通需要的最低成本。如果输入数据不足以保证畅通,则输出−1,表示需要建设更多公路。输入样例:6 151 2 51 3 3

    2022年8月8日
    7

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号