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.
$(function () {
$('pre.prettyprint code').each(function () {
var lines = $(this).text().split('\n').length;
var $numbering = $('
$(this).addClass('has-numbering').parent().append($numbering);
for (i = 1; i ').text(i));
};
$numbering.fadeIn(1700);
});
});
Resist the Temptation of the Singleton Pattern的更多相关文章
- The Java Enum: A Singleton Pattern [reproduced]
The singleton pattern restricts the instantiation of a class to one object. In Java, to enforce this ...
- Net设计模式实例之单例模式( Singleton Pattern)
一.单例模式简介(Brief Introduction) 单例模式(Singleton Pattern),保证一个类只有一个实例,并提供一个访问它的全局访问点.单例模式因为Singleton封装它的唯 ...
- 深入浅出设计模式——单例模式(Singleton Pattern)
模式动机对于系统中的某些类来说,只有一个实例很重要,例如,一个系统中可以存在多个打印任务,但是只能有一个正在工作的任务:一个系统只能有一个窗口管理器或文件系统:一个系统只能有一个计时工具或ID(序号) ...
- 浅谈设计模式--单例模式(Singleton Pattern)
题外话:好久没写blog,做知识归纳整理了.本来设计模式就是个坑,各种文章也写烂了.不过,不是自己写的东西,缺少点知识的存在感.目前还没做到光看即能记住,得写.所以准备跳入设计模式这个大坑. 开篇先贡 ...
- .NET设计模式(2):单件模式(Singleton Pattern)(转载)
概述 Singleton模 式要求一个类有且仅有一个实例,并且提供了一个全局的访问点.这就提出了一个问题:如何绕过常规的构造器,提供一种机制来保证一个类只有一个实例?客户程 序在调用某一个类时,它是不 ...
- 单件模式(Singleton Pattern)(转)
概述 Singleton模式要求一个类有且仅有一个实例,并且提供了一个全局的访问点.这就提出了一个问题:如何绕过常规的构造器,提供一种机制来保证一个类只有一个实例?客户程序在调用某一个类时,它是不会考 ...
- 设计模式之单例模式(Singleton Pattern)
单例模式 单例模式(Singleton Pattern)在java中算是最常用的设计模式之一,主要用于控制控制类实例的数量,防止外部实例化或者修改.单例模式在某些场景下可以提高系统运行效率.实现中的主 ...
- Learning JavaScript Design Patterns The Singleton Pattern
The Singleton Pattern The Singleton pattern is thus known because it restricts instantiation of a cl ...
- 深入设计模式(二)——单例模式(Singleton Pattern)
一.单例模式介绍 单例模式(Singleton Pattern),保证一个类只有一个实例,并提供一个访问它的全局访问点.单例模式因为Singleton封装它的唯一实例,它就可以严格地控制客户怎样访问它 ...
随机推荐
- C++中(int&)和(int)的区别
在说这个问题之前,先说两个需要知道的背景知识: (1)语言的类型的强制转换不会修改原来的数据,会另外的开辟一个临时的或者程序中指定的空间来存储强制转换后的值. (2)C++引用的实现是在符号表中动了手 ...
- Python学习之路——类
类: 类是将抽象的实物进行的划分. 在现实世界中如果我们将: 人类包含:男人.女人.孩子.老人等动物类包含:小猫.小狗.小兔子等 在代码世界中我也可以分类,例如将相同功能的代码放到一起,这就是分类. ...
- cocos2d-x游戏开发系列教程-超级玛丽07-CMGameMap(三)-按键处理
在地图初始化好了之后,就开始移动马里奥吧,我在windows下,是使用键盘来移动马里奥的 w是跳,d是前进,a是后退,那么在程序里是怎么来获取这个按键的呢? 普通的windows程序,在按键之后,会有 ...
- sqlserver 三种恢复模式
sql server数据库提供了三种恢复模式:完整,简单和大容量日志,这些模式决定了sql server如何使用事务日志,如何选择它要记录的操作,以及是否截断日志.截断事务日志是删除己执行事务并把该日 ...
- 【Maven】pom.xml 配置 eclipse错误
<!-- servlet --> <dependency> <groupId>javax.servlet</groupId> <artifactI ...
- Automatic Preferred Max Layout Width is not available on iOS versions prior to 8.0
今天在真机调试低版本系统的时候出现如题类似Layout Max Width在ios 8 之前不适用的问题, 初步估计是autolayout 所导致的 查找资料解决方法如下: 将label下Preffe ...
- BZOJ 3040: 最短路(road) ( 最短路 )
本来想学一下配对堆的...结果学着学着就偏了... 之前 kpm 写过这道题 , 前面的边不理它都能 AC .. 我也懒得去写前面的加边了... 用 C++ pb_ds 库里的 pairing_hea ...
- BZOJ 2016: [Usaco2010]Chocolate Eating( 二分答案 )
因为没注意到long long 就 TLE 了... 二分一下答案就Ok了.. ------------------------------------------------------------ ...
- ASP.net 学习路线(详细)
.net学习路线 入门篇1. 学习面向对象(OOP)的编程思想 许多高级语言都是面向对象的编程,.NET也不例外.如果您第一次接触面向对象的编程,就必须理解类.对象.字段.属性.方法和 ...
- 我的Python成长之路---第四天---Python基础(15)---2016年1月23日(寒风刺骨)
二.装饰器 所谓装饰器decorator仅仅是一种语法糖, 可作用的对象可以是函数也可以是类, 装饰器本身是一个函数, 其主要工作方式就是将被装饰的类或者函数当作参数传递给装饰器函数.本质上, ...