单例模式

单身模式
维基百科,自由的百科全书

举例说明单身模式的类图。
在软件工程中,单例模式是一种软件设计模式,它将一个类的实例化限制为一个对象。当需要恰好一个对象来协调系统中的操作时,这非常有用。这个概念有时候被推广到当只有一个对象存在时更高效地运行的系统,或者限制实例化到一定数量的对象的系统。这个术语来自单身人士的数学概念。

有些人对单身模式持批判态度,并认为这是一种反模式,因为它经常被用在不利于情况的场合,在实际上不需要一个类的唯一实例的情况下引入不必要的限制,并将全局状态引入到应用程序中。[1] [2] [3]

内容 [ 隐藏 ]
1 概述
2 常见用途
3 在哪里使用它
4 实施
4.1 懒惰初始化
5 注释
6 参考
7 外部链接
概述[ 编辑]
Singleton [4]设计模式是23个着名的GoF设计模式之一,它描述了如何解决重复出现的设计问题,以设计灵活和可重用的面向对象软件,也就是更容易实现,更改,测试和重用。

Singleton设计模式解决了如下问题: [5]

如何确保一个班级只有一个实例?
如何轻松访问一个类的唯一实例?
一个类如何控制它的实例?
怎样才能限制一个类的实例呢?
Singleton设计模式描述了如何解决这些问题:

隐藏类的构造函数。
定义一个公共静态操作(getInstance()),返回该类的唯一实例。
这种模式的关键思想是让类本身负责控制它的实例化(它只实例化一次)。
隐藏的构造函数(声明为private)确保类不能从类外部实例化。
通过使用类名称和操作名称(Singleton.getInstance()),可以轻松访问公共静态操作。

常见用途[ 编辑]
该抽象工厂,建设者和原型模式可以在它们的实现使用单身人士。
方式信息辛范范范辛范范内亦范挥信范亦信信段
状态对象通常是单身人士。
Singletons are often preferred to global variables because:
They do not pollute the global namespace (or, in languages with namespaces, their containing namespace) with unnecessary variables.[4]
They permit lazy allocation and initialization, whereas global variables in many languages will always consume resources.
Where to use it[edit]
When only one instance or a specific number of instances of a class are allowed. Facade objects are often Singletons because only one Facade object is required[citation needed].

Implementation[edit]
An implementation of the singleton pattern must:

ensure that only one instance of the singleton class ever exists; and
provide global access to that instance.
Typically, this is done by:

declaring all constructors of the class to be private; and
providing a static method that returns a reference to the instance.
The instance is usually stored as a private static variable; the instance is created when the variable is initialized, at some point before the static method is first called. The following is a sample implementation written in Java.

public final class Singleton {
private static final Singleton INSTANCE = new Singleton();

private Singleton() {}

public static Singleton getInstance() {
    return INSTANCE;
}

}
Lazy initialization[edit]
A singleton implementation may use lazy initialization, where the instance is created when the static method is first invoked. If the static method might be called from multiple threads simultaneously, measures may need to be taken to prevent race conditions that could result in the creation of multiple instances of the class. The following is a thread-safe sample implementation, using lazy initialization with double-checked locking, written in Java.[a]

public final class Singleton {
private static volatile Singleton instance = null;

private Singleton() {}

public static Singleton getInstance() {
    if (instance == null) {
        synchronized(Singleton.class) {
            if (instance == null) {
                instance = new Singleton();
            }
        }
    }
    return instance;
}

}
Notes[edit]
Jump up ^ In Java, to avoid the synchronization overhead while keeping lazy initialization with thread safety, the preferred approach is to use the initialization-on-demand holder idiom.[citation needed]
References[edit]
Jump up ^ Scott Densmore. Why singletons are evil, May 2004
Jump up ^ Steve Yegge. Singletons considered stupid, September 2004
Jump up ^ Clean Code Talks - Global State and Singletons
^ Jump up to: a b Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides (1994). Design Patterns: Elements of Reusable Object-Oriented Software. Addison Wesley. pp. 127ff. ISBN 0-201-63361-2.
Jump up ^ “The Singleton design pattern - Problem, Solution, and Applicability”. w3sDesign.com. Retrieved 2017-08-16.
External links[edit]

This article’s use of external links may not follow Wikipedia’s policies or guidelines. Please improve this article by removing excessive or inappropriate external links, and converting useful links where appropriate into footnote references. (November 2016) (Learn how and when to remove this template message)
The Wikibook Computer Science/Design Patterns has a page on the topic of: Singleton implementations in various languages
Wikimedia Commons has media related to Singleton pattern.
Complete article “Singleton Design Pattern techniques”
Four different ways to implement singleton in Java “Ways to implement singleton in Java”
Book extract: Implementing the Singleton Pattern in C# by Jon Skeet
Singleton at Microsoft patterns & practices Developer Center
IBM article “Double-checked locking and the Singleton pattern” by Peter Haggar
IBM article “Use your singletons wisely” by J. B. Rainsberger
Javaworld article “Simply Singleton” by David Geary
Google article “Why Singletons Are Controversial”
Google Singleton Detector (analyzes Java bytecode to detect singletons)
[hide] v t e
Software design patterns
Gang of Four
patterns
Creational
Abstract factory Builder Factory method Prototype Singleton
Structural
Adapter Bridge Composite Decorator Facade Flyweight Proxy
Behavioral
Chain of responsibility Command Interpreter Iterator Mediator Memento Observer State Strategy Template method Visitor
Concurrency
patterns
Active object Balking Binding properties Double-checked locking Event-based asynchronous Guarded suspension Join Lock Monitor Proactor Reactor Read write lock Scheduler Thread pool Thread-local storage
Architectural
patterns
Front controller Interceptor MVC ADR ECS n-tier Specification Publish–subscribe Naked objects 服务定位器 有效的记录 身份地图 数据访问对象 数据传输对象 控制倒置 模型2
其他
模式
黑板 业务代表 复合实体 依赖注入 拦截过滤器 延迟加载 模拟对象 空对象 对象池 仆人 双胞胎 输入隧道 方法链接
图书
设计模式 企业集成模式

Christopher Alexander Erich Gamma 拉尔夫·约翰逊 约翰Vlissides Grady Booch 肯特·贝克 病房坎宁安 马丁福勒 罗伯特·马丁 Jim Coplien 道格拉斯·施密特 琳达瑞星
社区
山坡小组 波特兰模式库
类别:软件设计模式反模式
导航菜单
未登录谈论捐款创建帐号登录文章谈论读编辑查看历史搜索

Search Wikipedia

主页
内容
典型内容
现在发生的事
随机文章
捐赠给维基百科
维基百科商店
相互作用
帮帮我
关于维基百科
社区门户
最近的变化
联系页面
工具
什么链接在这里
相关更改
上传文件
特殊页面
永久链接
页面信息
Wikidata项目
引用此页
打印/导出
创建一本书
下载为PDF
可打印版本
在其他项目
维基共享资源
维基教科书
语言
Български
加泰罗尼亚语
Čeština
德语
西班牙语
فارسی
法语
加里西亚
한국어
Հայերեն
意大利语
עברית
匈牙利
മലയാളം
荷兰
日本语
挪威
波兰语
葡萄牙语
Русский
Српски/ srpski
瑞典语
தமிழ்
ไทย
Türkçe
Українська
TiếngViệt
中文
编辑链接
本页面最后编辑于2017年11月5日00:06。
文字下是可用的知识共享署名-相同方式共享许可 ; 附加条款可能适用。使用本网站即表示您同意使用条款和隐私政策。维基百科®是维基媒体基金会,一个非营利组织的注册商标。
隐私政策关于维基百科免责声明联系维基百科开发商Cookie语句移动视图Wikimedia Foundation Powered by MediaWiki

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值