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


相关推荐

  • pycharm的配置_pycharm怎么配置python环境变量

    pycharm的配置_pycharm怎么配置python环境变量一、Python解释器1、Python解释器计算机只能读懂0和1这样的二进制编码文件,所以需要一个东西将Python程序解释成计算机可以读懂并执行的二进制文件,这个东西就是Python解释器。在PyCharm中运行Python代码,您需要配置至少一个Python解释器。PyCharm支持以下解释器类型: 源Python解释器; 虚拟环境:(Virtualenv,Pipenv,andConda); 其他Python实现(IronP.

    2022年8月28日
    0
  • python获取股票历史数据_量化交易之如何获取股票历史数据并存为csv

    python获取股票历史数据_量化交易之如何获取股票历史数据并存为csv量化研究尤其是进行基于价值投资的量化研究,需要上市公司的历史估值数据,如市盈率PE,市净率PB,或者市销率PS,市现率PCF。而有的人喜欢用exce或者csv文件的格式存放数据并且分析。我这里介绍一个网站,BaoStock,既支持直接下载历史数据为csv,也支持用程序下载数据并生成csv格式。网站地址是www.baostock.com,如果要下载历史估值数据,进入首页后,选择“沪深A股估值指标(日…

    2022年6月24日
    37
  • MyBatis入门学习(一)

    MyBatis入门学习(一)

    2021年12月10日
    39
  • 激活码pycharm_通用破解码

    激活码pycharm_通用破解码,https://javaforall.net/100143.html。详细ieda激活码不妨到全栈程序员必看教程网一起来了解一下吧!

    2022年3月16日
    32
  • Mac OS mojave, Big Sur 内置读写NTFS[通俗易懂]

    Mac OS mojave, Big Sur 内置读写NTFS[通俗易懂]MacOSmojave,BigSur内置读写NTFS注意事项:你的NTFS磁盘命名不要出现空格,下划线等特殊字符。详细流程插上硬盘后,查看你的硬盘名称,这里假设名称是硬盘名字,例如XiangguoNTFS(你的NTFS磁盘命名不要出现空格,下划线等特殊字符)打开Terminal,你也可以直接spotlight输入terminal打开。在终端输入sudonano/etc/fstab敲击回车现在你看到了一个编辑界面,输入LABEL=XiangguoNTFSnonentfs

    2022年6月21日
    44
  • pytest parametrize fixture_参数化数据

    pytest parametrize fixture_参数化数据前言当某个接口中的一个字段,里面规定的范围为1-5,你5个数字都要单独写一条测试用例,就太麻烦了,这个时候可以使用pytest.mark.parametrize装饰器可以实现测试用例参数化。官方示

    2022年7月29日
    4

发表回复

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

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