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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • WebService简单案例实例

    WebService简单案例实例本周工作日即将结束,下周项目经理安排了一项任务可能需要使用到webservice,但本人之前尚未使用过,网上查了一些案例看了看在此小记一篇留作日后回首也希望可以帮助到查看者朋友1、什么是WebService?WebService是一种远程调用技术,也叫XMLWebServiceWebService,是一种可以接收从Internet或者Internet上的其他系统中传递过来的请求,轻量级的独…

    2022年7月21日
    13
  • 有什么优质的计算机专业书籍?操作系统、计算机网络、计算机组成、数据结构、数据库…..「建议收藏」

    有什么优质的计算机专业书籍?操作系统、计算机网络、计算机组成、数据结构、数据库…..「建议收藏」大家好,我是小林哥。平日里,大家都喊程序员加班多很辛苦,动不动就掉头发,但干的还是很香的,毕竟大多数公司钱还是给的很到位的,今年毕业应届生的我见到好多动不动就月薪20K~30K的,真让人两眼泪酸酸,当然这离不开他们大学期间的努力。讲真,没什么家庭背景的人,选择当程序员确实是比较好的选择了,原因有二:首先,当今互联网、AI人工智能、大数据等都是高速发展的行业,自然人才需求很多,薪资也相对其他传统行业高;第二,纯粹看你技术能力,只要自己愿意付出努力,技术能力肯定会慢慢提高上来,而且现在比起几十年

    2022年5月2日
    44
  • 手机号码正则(已测试可以)

    手机号码正则(已测试可以)

    2021年10月19日
    35
  • 算法设计克林伯格pdf_LSTM算法

    算法设计克林伯格pdf_LSTM算法第一部分 levmar的安装与使用 Levenberg-Marquardt算法是求解非线性问题的一个非常好用的算法。该算法属于信赖域算法的一种,关于信赖域算法的解释可以参考这一博主的解释:关于信赖域算法理解,个人感觉很好。    Levenberg-Marquardt算法是一个开源的算法,其文件下载地址如下:http://www.netlib.org/clapack/C

    2022年10月1日
    0
  • JVM优化[通俗易懂]

    JVM优化[通俗易懂]为什么要进行JVM优化?在本地开发环境中我们很少有需求对JVM进行优化,但是到了生产环境我们的程序可能出现如下问题:运行的引用“卡住了”,日志不输出,程序没反应服务器的CPU负载突然升高在多线程应用下,如何合理的分配线程的数量。。。。。。。。。通过Java-server和java-client设置JVM的运行参数serverVM的初始堆空间会大一些,默认使用的是并行垃圾回…

    2022年4月28日
    46
  • python基础系列教程——Python的安装与测试:python解释器、PyDev编辑器、pycharm编译器

    python基础系列教程——Python的安装与测试:python解释器、PyDev编辑器、pycharm编译器全栈工程师开发手册(作者:陈玓玏)python教程全解白手起家,从头开启python的开发环境搭建。一.如何安装Python在https://www.python.org/下载安装包。下载下来一个exe文件,直接双击运行。选择InstallNow,立即安装。配置环境变量:右键开始——控制面板——系统——高级系统配置——环境变量。找…

    2022年7月23日
    11

发表回复

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

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