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.

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

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

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • Vuthink正确安装过程

    Vuthink正确安装过程

    2021年10月11日
  • verilog语言与VHDL_vhdl程序设计

    verilog语言与VHDL_vhdl程序设计今年开始接触更改产品的FPGA代码,感觉公司虽然搞了很多年了,但是FPGA这块缺乏一些“软件工程”上的概念导入。如果对于Altera/Xilinx公司,如果做IP库,可能需要考虑各种编译器的兼容性,不能引入太多的“高级”语法,但是,对于一个公司而言,我认为代码的可维护性是放在第一位的,是在编译器兼容性之类之上的要求。1.VHDL总体而言,VHDL提供了如下一些语法特性,用于简化代码:1.1record和type定义例如对于KM1024i喷头控制,我们可以定义如下: –喷头控

  • ConnectionStrings 连接字符串「建议收藏」

    ConnectionStrings 连接字符串「建议收藏」<connectionStrings><addname=”sqliteContext”connectionString=”DataSource=E:\WHPCodeLiberary\temp\SqlLiteDBs\TestDB.s3db;Version=3;New=True;”providerName=”System.Data.SQLite”/>…

  • 使用Java代码过滤掉乱码字符

    使用Java代码过滤掉乱码字符转自:http://www.cnblogs.com/en-heng/p/5320024.html最近在日志数据清洗时遇到中文乱码,如果只要有非中文字符就将该字符串过滤掉,这种方法虽简单但并不可取,因为比如像Xperia™主題、天天四川麻将Ⅱ这样的字符串也会被过滤掉。1.Unicode编码Unicode编码是一种涵盖了世界上所有语言、标点等字符的编码方式,简单一点说

  • stardict 安装真人发声包

    stardict 安装真人发声包

  • Android解析XML文件[通俗易懂]

    Android解析XML文件[通俗易懂]按计划每周更新一篇技术博文,第一篇:《Android解析XML文件》一、在Android应用中的XML文件来源1、本地xml文件  本地XML文件可以放在应用根目录assets文件夹、res/xml、res/raw、SDcard卡、应用的data目录等;除res/xml可直接通过getXml(intid)获取XML文档,返回一个解析器对象(XmlResourcePar

发表回复

您的电子邮箱地址不会被公开。

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