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 = $('

    ').addClass('pre-numbering').hide();
    $(this).addClass('has-numbering').parent().append($numbering);
    for (i = 1; i ').text(i));
    };
    $numbering.fadeIn(1700);
    });
    });

Resist the Temptation of the Singleton Pattern的更多相关文章

  1. The Java Enum: A Singleton Pattern [reproduced]

    The singleton pattern restricts the instantiation of a class to one object. In Java, to enforce this ...

  2. Net设计模式实例之单例模式( Singleton Pattern)

    一.单例模式简介(Brief Introduction) 单例模式(Singleton Pattern),保证一个类只有一个实例,并提供一个访问它的全局访问点.单例模式因为Singleton封装它的唯 ...

  3. 深入浅出设计模式——单例模式(Singleton Pattern)

    模式动机对于系统中的某些类来说,只有一个实例很重要,例如,一个系统中可以存在多个打印任务,但是只能有一个正在工作的任务:一个系统只能有一个窗口管理器或文件系统:一个系统只能有一个计时工具或ID(序号) ...

  4. 浅谈设计模式--单例模式(Singleton Pattern)

    题外话:好久没写blog,做知识归纳整理了.本来设计模式就是个坑,各种文章也写烂了.不过,不是自己写的东西,缺少点知识的存在感.目前还没做到光看即能记住,得写.所以准备跳入设计模式这个大坑. 开篇先贡 ...

  5. .NET设计模式(2):单件模式(Singleton Pattern)(转载)

    概述 Singleton模 式要求一个类有且仅有一个实例,并且提供了一个全局的访问点.这就提出了一个问题:如何绕过常规的构造器,提供一种机制来保证一个类只有一个实例?客户程 序在调用某一个类时,它是不 ...

  6. 单件模式(Singleton Pattern)(转)

    概述 Singleton模式要求一个类有且仅有一个实例,并且提供了一个全局的访问点.这就提出了一个问题:如何绕过常规的构造器,提供一种机制来保证一个类只有一个实例?客户程序在调用某一个类时,它是不会考 ...

  7. 设计模式之单例模式(Singleton Pattern)

    单例模式 单例模式(Singleton Pattern)在java中算是最常用的设计模式之一,主要用于控制控制类实例的数量,防止外部实例化或者修改.单例模式在某些场景下可以提高系统运行效率.实现中的主 ...

  8. Learning JavaScript Design Patterns The Singleton Pattern

    The Singleton Pattern The Singleton pattern is thus known because it restricts instantiation of a cl ...

  9. 深入设计模式(二)——单例模式(Singleton Pattern)

    一.单例模式介绍 单例模式(Singleton Pattern),保证一个类只有一个实例,并提供一个访问它的全局访问点.单例模式因为Singleton封装它的唯一实例,它就可以严格地控制客户怎样访问它 ...

随机推荐

  1. 设计模式值六大原则——依赖倒置原则 (DIP)

    依赖倒置原则(Dependence Inversion Principle,DIP)的原始定义: 高层模块不应该依赖底层模块,两者都应该依赖其抽象: 抽象不应该依赖细节: 细节应该依赖抽象. 依赖倒置 ...

  2. HTML5 总结-表单-表单元素

    HTML5 表单元素 HTML5 的新的表单元素: HTML5 拥有若干涉及表单的元素和属性. 本章介绍以下新的表单元素: datalist keygen output 浏览器支持 Input typ ...

  3. win7 VMware Workstation Centos6.5虚机桥接上网设置 详解(靠谱)

    1.VMware Workstation 设置 2. vim /etc/sysconfig/network-scripts/ifcfg-eth0 NAME="System eth0" ...

  4. python2.7_1.2_打印设备名和IPv4地址

    代码如下: # -*- coding: utf-8 -*- import socket def print_machine_info(): host_name = socket.gethostname ...

  5. Objective-C 程序设计第四版 二

    1,%@  是用于输出OC里面的对象.例如 NSString *str = @“ls kd kd kf ”; NSLog(@“%@“, str); 2,NSInteger不是一个对象,而是基本数据类型 ...

  6. CentOS 6.5系统安装配置图解教程(详细图文)

    转载:http://www.jb51.net/os/128751.html

  7. 顺为资本CEO许达来:为什么说中国创业者很幸福?(附PPT)

    顺为资本创始合伙人许达来 编者按:许达来,顺为资本创始合伙人及CEO,代表性投资项目包括小米科技.丁香园.一起作业.加一联创.金山软件及兴达国际等. 本文为许达来在新浪创业举办的新创课活动上的内容分享 ...

  8. Android Paint、Canvas、Matrix使用讲解(一、Paint)

    http://blog.csdn.net/tianjian4592/article/details/44336949 好了,前面主要讲了Animation,Animator 的使用,以及桌面火箭效果和 ...

  9. JS - 删除确认

    <a href="javascript:if(confirm('确实要删除吗?'))location='<{:U('Admin/Update/deleteuserinfo', a ...

  10. 版本管理工具:linux下svn的基本使用

    参考: linux下安装SVN    http://jingyan.baidu.com/article/3c343ff7039de20d37796306.html svn客户端使用linux篇  ht ...