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)
上一篇 2022年1月25日 下午5:00
下一篇 2022年1月25日 下午6:00


相关推荐

  • flex布局垂直居中

    flex布局垂直居中使用flex布局实现下面图中效果:外框高都为400px,边框为2px;圆的宽高为100px;中圆是水平居中;下圆是水平居中以及相对于中圆垂直居中(下圆到中圆的距离和下圆到下边框的距离相等)。效果如图:我的实现方法是笨办法,大佬们多指点<divclass=”box”><divclass=”item”><divclass=”child”></div></di

    2022年6月12日
    39
  • FLP 定理

    FLP 定理FLP 定理在异步通信场景 即使只有一个进程失败了 没有任何算法能够保证进程能够达到一致性系统模型系统模型 1 1 异步通信 gt 异步通信与同步通信最大区别是没有时钟 不能时间同步 不能使用超时 不能探测失败 消息可任意延迟 消息可乱序 1 2 通信健壮 gt 只要进程非失败 消息虽会被无限延迟 但最终会被送达 且消息只会被送达一次 无重复 1 3Fail Stop 模型 gt 进程失败如同宕机 不再处理任何消息 相对 Byzantine 模型 不会产生错误消息 1 4 协议约束

    2026年3月17日
    2
  • 点积与叉乘的运算与物理意义

    点积与叉乘的运算与物理意义点积与叉乘的运算与物理意义

    2026年3月19日
    2
  • 非常详细的rsyslogd配置文件解析

    非常详细的rsyslogd配置文件解析Rsyslog配置文件详解发表于2年前(2014-02-1017:25)  阅读(9805) | 评论(3) 10人收藏此文章, 我要收藏赞1rsyslog服务和logrotate服务======================================================================rsyslog是一个sysl

    2022年8月15日
    14
  • n8n邪修指南:三步撬开Coze墙角,让它的优势成为你的便利

    n8n邪修指南:三步撬开Coze墙角,让它的优势成为你的便利

    2026年3月15日
    3
  • 实际项目中如何使用Git做分支管理「建议收藏」

    实际项目中如何使用Git做分支管理「建议收藏」记得刚工作的时候根本不知道什么是版本管理工具,有一次和别人聊天,人家问你们公司代码用什么版本管理工具?我说啥是版本管理工具,我们一般用U盘拷贝,然后人家就顾左右而言他了。后来我知道了有个东西叫,后来又知道了还有个东西叫。所以说刚毕业的同学一定要优先进入专业的大公司,就像年轻时候应该去大城市闯两年一样,眼界以及你遇到的牛人会大大加快你以后成功的进程。本文主要是介绍一种在具体实践中使用Git来管理项目开发的一种成功的方式,其实主要思想来源于这篇文章Asuccessful…

    2022年10月1日
    8

发表回复

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

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