当前位置: 首页 > 编程日记 > 正文

singleton设计模式_让我们研究一下Singleton设计模式的优缺点

singleton设计模式

by Navdeep Singh

通过Navdeep Singh

让我们研究一下Singleton设计模式的优缺点 (Let’s examine the pros and cons of the Singleton design pattern)

Design patterns are conceptual tools for solving complex software problems. These patterns are simple and elegant solutions that have evolved over time and may have become generally accepted as the best way to address certain design challenges. — Me, in my ebook Reactive Programming with Swift 4

设计模式是解决复杂软件问题的概念工具。 这些模式是简单而优雅的解决方案,并且随着时间的推移而发展,并且可能已被广泛接受为解决某些设计挑战的最佳方法。 — 我在我的电子书《使用Swift 4进行React式编程》中

单例设计模式 (Singleton Design Pattern)

The Singleton pattern encapsulates a shared resource within a single unique class instance. This instance arbitrates access to the resource and storage-related state information. A class method provides the reference to this instance, so there is no need to pass the reference around. Any object that has access to the Singleton’s class header can use the Singleton.

Singleton模式将共享资源封装在一个唯一的类实例中。 该实例仲裁对资源和与存储相关的状态信息的访问。 类方法提供对此实例的引用,因此不需要传递该引用。 任何有权访问Singleton类标题的对象都可以使用Singleton。

This design pattern defines the structure of a class that can have only one instance. A Singleton encapsulates a unique resource and makes it readily available throughout the application. The resource might be hardware, a network service, a persistent store, or anything else that can be modeled as a unique object or service.

这种设计模式定义了只能具有一个实例的类的结构。 Singleton封装了独特的资源,并使其易于在整个应用程序中使用 。 该资源可以是硬件,网络服务,持久性存储,或可以建模为唯一对象或服务的其他任何资源。

One example from Cocoa touch is a physical device running an iOS application. For an executing app, there is only one iPhone or iPad with a single battery and a screen. UIDevice is a Singleton class here since it provides one channel to interact with the underlying features. In case the unique resource has a writable configuration, this sort of discrepancy can lead to problems such as race condition and deadlock. Since they are unique, Singletons act as a control, ensuring orderly access to the shared resource.

来自Cocoa touch的一个示例是运行iOS应用程序的物理设备。 对于执行中的应用程序,只有一部iPhone或iPad带有一个电池和一个屏幕。 UIDevice在这里是Singleton类,因为它提供了一个与基础功能进行交互的渠道。 如果唯一资源具有可写配置,则这种差异会导致诸如争用条件和死锁之类的问题。 由于它们是唯一的,因此Singletons充当控件,确保对共享资源的有序访问。

Singletons may often be modeled as a server within the application that accepts requests to send, store, or retrieve data and configure the resource state.
单例通常可以建模为应用程序中的服务器,该服务器接受发送,存储或检索数据并配置资源状态的请求。

实作 (Implementation)

Implementation of the Singleton pattern often typically creates a single object using the factory method, and this instance/object is called a shared instance in most cases. Since the access to the instance is passed on through a class method, the need to create an object is eliminated. Let’s look at the Singleton implementation in code.

Singleton模式的实现通常通常使用factory方法创建单个对象,并且在大多数情况下,此实例/对象称为共享实例。 由于对实例的访问是通过类方法传递的,因此无需创建对象。 让我们看一下代码中的Singleton实现。

For this example, we have used the command line tool Xcode template to create a project and name it Singleton. Our Singleton class is called SingletonObject, which we created as a normal Cocoa class, and it is a subclass of NSObject. The project setup looks like this so far:

在此示例中,我们使用了命令行工具 Xcode模板来创建一个项目并将其命名为Singleton。 我们的Singleton类称为SingletonObject ,它是我们作为普通Cocoa类创建的,它是NSObject的子类。 到目前为止,项目设置如下:

Then we added a class method called sharedInstance as discussed earlier since this is how the class will make the Singleton available. Its return value is of the SingleObject type, as follows:

然后, 如前所述 ,我们添加了一个名为sharedInstance的类方法,因为这是该类使Singleton可用的方式。 它的返回值是SingleObject类型,如下所示:

func sharedInstance() -> SingletonObject {         }

The function stores the instance in a static local reference called localSharedInstance. Static locals are much like global objects — they retain their value for the lifetime of the application, yet they are limited in scope. These qualities make them ideal to be a Singleton, since they are permanent and yet ensure that our Singleton is only available through sharedInstance.

该函数将实例存储在称为localSharedInstance的静态本地引用中。 静态局部变量很像全局对象,它们在应用程序的生命周期中保留其价值,但范围有限。 这些品质使它们非常适合成为Singleton,因为它们是永久性的,而且可以确保我们的Singleton仅可通过sharedInstance获得

This is one of the ways in which our Singleton implementation ensures that the Singleton stays singular. The basic structure of shared instance consists of a conditional block that tests whether a Singleton instance has been allocated. But surprisingly, that’s the older way of doing things (or may be the way to go in other languages). In Swift, however, the implementation has changed to merely one line, and we don’t require a method. The implementation looks like this:

这是我们的Singleton实现可确保Singleton保持单数的方式之一。 共享实例的基本结构由一个条件块组成,该条件块测试是否已分配Singleton实例。 但是令人惊讶的是,这是较旧的处理方式(或者可能是其他语言的处理方式)。 但是,在Swift中,实现只更改为一行,我们不需要方法。 实现看起来像这样:

class SingletonObject: NSObject {    static let sharedInstance = SingletonObject()}

Simple, isn’t it?

很简单,不是吗?

单例设计模式—优点和缺点 (Singleton design pattern — Pros and cons)

Singletons are not the answer to every problem. Like any tool, they can be short in supply or can be overused.
单例并不能解决所有问题。 像任何工具一样,它们可能供应不足或过度使用。

Some developers are critical of Singletons for various reasons. We will examine this critique and discuss ways to address them briefly. The criticisms, for the most part, fall into two categories:

一些开发人员出于各种原因对Singletons持批评态度。 我们将研究这种批评并讨论解决这些问题的方法。 批评大部分分为两类:

  • Singletons hinder unit testing: A Singleton might cause issues for writing testable code if the object and the methods associated with it are so tightly coupled that it becomes impossible to test without writing a fully-functional class dedicated to the Singleton.

    Singleton会阻碍单元测试:如果对象和与之关联的方法紧密耦合,以至于如果不编写专用于Singleton的功能齐全的类就无法进行测试,则Singleton可能会导致编写可测试代码的问题。

  • Singletons create hidden dependencies: As the Singleton is readily available throughout the code base, it can be overused. Moreover, since its reference is not completely transparent while passing to different methods, it becomes difficult to track.

    单例创建隐藏的依赖项:由于单例在整个代码库中都很容易获得,因此可能会被过度使用。 此外,由于在传递给不同方法时其引用不是完全透明的,因此变得难以跟踪。

To avoid these complications, when considering the Singleton pattern, you should make certain that the class is a Singleton. Also, while thinking of designing the Singleton design pattern, keep testing in mind and use dependency injection whenever possible — that is, try to pass the Singleton as a parameter to the initializer whenever possible.

为了避免这些复杂性,在考虑Singleton模式时,应确保该类是Singleton。 另外,在考虑设计Singleton设计模式时,请牢记测试并在可能的情况下使用依赖注入-也就是说,尝试在可能的情况下将Singleton作为参数传递给初始化程序。

For other updates, you can follow me on Twitter on my twitter handle @NavRudraSambyal

对于其他更新,您可以在Twitter上的@NavRudraSambyal上关注我。

To read more about various other Design patterns and practice examples, you can follow the link to my book Reactive programming in Swift 4

要阅读有关其他各种设计模式和实践示例的更多信息,可以单击我的书《 Swift 4中的React式编程》中的链接。

Thanks for reading, please share it if you found it useful :)

感谢您的阅读,如果您觉得有用,请分享:)

翻译自: https://www.freecodecamp.org/news/singleton-design-pattern-pros-and-cons-e10f98e23d63/

singleton设计模式

相关文章:

【转】MFC消息映射详解(整理转载)

消息:主要指由用户操作而向应用程序发出的信息,也包括操作系统内部产生的消息。例如,单击鼠标左按钮,windows将产WM_LBUTTONDOWN消息,而释放鼠标左按钮将产生WM_LBUTTONUP消息,按下键盘上的字母键&#xff…

php 2 往数据库添加数据

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 前端代码: function submit_result() { $.post("Controllers/ajaxController.php",{"name": $("#name").val(),"mobile": $("#mo…

设计模式:单例

传统的实现方法:两私一公,涉及线程安全问题(即使有多重检查锁也可以通过反射破坏单例)public class Singleton {private volatile static Singleton instance null;private Singleton () {}public static Singleton getSingleton…

100天59万行代码_如何抽出100天的代码时间

100天59万行代码Life moves pretty fast. If you don’t stop and look around once in a while, you could miss it. — Ferris Bueller生活发展很快。 如果您不停地走动,不时环顾四周,您可能会错过它。 —摩天轮 My time at freeCodeCamp was a fun an…

Mac 安装SecureCRT

scrt-8.0.2-1118.osx_x64.dmg https://pan.baidu.com/s/1miS5XVy 1.下载破解文件 SecureCRT https://pan.baidu.com/s/1eRW5IfS 2. 打开终端执行 chmod x ~/Downloads/SecureCRT 替换破解文件SecureCRT到/Applications/SecureCRT.app/Contents/MacOS/ 3. 打开SecureCRT&#xf…

PHP 3 HTML POST带参数请求 后端返回json格式的数据给前端

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 前端代码 <!DOCTYPE html> <html lang"zh"><head><meta charset"UTF-8"><title>Title</title><script src"https://ajax.aspnetcdn.c…

产品经理入门_所以您想成为产品经理? 这就是我的入门方式。

产品经理入门by Melanie Lei由Melanie Lei 所以您想成为产品经理&#xff1f; 这就是我的入门方式。 (So you want to be a product manager? This is how I got started.) One of the most common questions I get asked is, “How do you get a Product Manager job if you…

又拍云SSL证书全新上线,提供一站式HTTPS安全解决方案

互联网快速发展&#xff0c;云服务早已融入每一个人的日常生活&#xff0c;而互联网安全与互联网的发展息息相关&#xff0c;这其中涉及到信息的保密性、完整性、可用性、真实性和可控性。又拍云上线了与多家国际顶级 CA 机构合作的数款OV & EV SSL证书&#xff0c;提供一站…

HDU 1155 Bungee Jumping

题意&#xff1a;英语水平太次…………读了好久好久好久才读懂OTZ James Bond要逃跑&#xff0c;跑到一个桥边上&#xff0c;要跳到地面&#xff0c;桥边有个有弹性的绳子长度为l&#xff0c;如果他跳下去能到达地面&#xff0c;但速度超过10就会摔死&#xff0c;否则能成功降落…

php 4 创建公共的链接数据库php文件并在其它文件引用它

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 创建公共文件 <? //1. 声明字符编码 header("Content-Type:text/html;charsetutf8"); //2. 连接数据库 $linkmysql_connect("localhost","root","root");/…

异步回调地狱_如何逃避异步/等待地狱

异步回调地狱async/await freed us from callback hell, but people have started abusing it — leading to the birth of async/await hell.async / await使我们从回调地狱中解脱出来&#xff0c;但是人们已经开始滥用它-导致async / await地狱的诞生。 In this article, I …

2015年编程之美(资格赛) ---2月29日

时间限制:2000ms单点时限:1000ms内存限制:256MB描述 给定两个日期&#xff0c;计算这两个日期之间有多少个2月29日&#xff08;包括起始日期&#xff09;。 只有闰年有2月29日&#xff0c;满足以下一个条件的年份为闰年&#xff1a; 1. 年份能被4整除但不能被100整除 2. 年份能…

2016多校赛2 A 数学推公式 E 极角排序,组合数(待补) L dp+bitset优化

2016 Multi-University Training Contest 2 A - Acperience 题意&#xff1a;给出w[]&#xff0c;求S((w[i]-aB[i])^2)的最小值(B[i]为1或-1)。 tags&#xff1a;一看到就搞了个三分上去&#xff0c;估计是精度问题&#xff0c;一直挖&#xff0c;23333。。 就是把这个公式推下…

php No 'Access-Control-Allow-Origin' header is present on the requested resource.'Ajax跨域访问解决方法

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 在PHP请求头加上 header("Access-Control-Allow-Origin: *");

二进制搜索算法_使用安全摄像机镜头解释二进制搜索算法

二进制搜索算法by Julia GeistJulia盖斯特(Julia Geist) 使用安全摄像机镜头解释二进制搜索算法 (Binary Search Algorithms explained using security camera footage) Binary search, also known as half-interval search or logarithmic search, is a search algorithm tha…

Codeforces 460E Roland and Rose(暴力)

题目链接&#xff1a;Codeforces 460E Roland and Rose 题目大意&#xff1a;在以原点为圆心&#xff0c;半径为R的局域内选择N个整数点&#xff0c;使得N个点中两两距离的平方和最大。 解题思路&#xff1a;R最大为30。那么事实上距离圆心距离最大的整数点只是12个最多&#x…

HTML POST提交参数给PHP并返回json,上传execl文件

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文&#xff1a; 需求&#xff1a;AJAX post带参数请求接口&#xff0c;PHP接收后存入数据库&#xff1b;然后返回json数据循环渲染到HTML <!DOCTYPE html> <html lang"zh">&l…

在Ubuntu 12.04 桌面上设置启动器(快捷方式)

在Ubuntu 12.04 桌面上设置启动器&#xff08;快捷方式&#xff09;过程讲解&#xff1a; 如下图所示&#xff0c;Eclipse 和 SQLDeveloper 都可以直接双击打开&#xff0c;这些应用程序的启动器都在 /usr/share/applications文件夹下面&#xff0c;进入后将其复制到桌面即可。…

rxswift中hud_如何在RxSwift中运行测试

rxswift中hudby Navdeep Singh通过Navdeep Singh 如何在RxSwift中运行测试 (How to run tests in RxSwift) RxTest and RxBlocking are part of the RxSwift repository. They are made available via separate pods, however, and so require separate imports.RxTest和RxBlo…

安装完DevExpress14.2.5,如何破解它呢?

DevExpress是一个界面控件套件&#xff0c;提供了一系列的界面控件套件的DotNet界面控件。DevExpress开发的控件有很强的实力&#xff0c;不仅功能丰富&#xff0c;应用简单&#xff0c;而且界面华丽&#xff0c;更可方便订制&#xff0c;方便开发人员开发。 下面介绍DevExpres…

Extjs Ext.TreePanel

TreePanel 简单实例。 <link rel"stylesheet" href"Js/ext-4.2/resources/css/ext-all-neptune.css"/><script src"Js/jQuery/jquery-1.8.2.min.js" type"text/javascript"></script><script src"Js/ext-…

php模糊搜索功能

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文&#xff1a; 前端 前端post请求并发送str参数>搜索的内容&#xff1b; PHP <?phpheader("Content-Type:text/html;charsetutf8"); header("Access-Control-Allow-Origin…

react 快速上手开发_React中测试驱动开发的快速指南

react 快速上手开发by Michał Baranowski通过MichałBaranowski React中测试驱动开发的快速指南 (A quick guide to test-driven development in React) Following the principles of Test-Driven Development (TDD) when writing a front-end React app might seem more dif…

iOS 相册和网络图片的存取

iOS 相册和网络图片的存取 保存 UIImage 到相册 UIKit UIKit 中一个古老的方法&#xff0c;Objective-C 的形式 void UIImageWriteToSavedPhotosAlbum(UIImage *image, id completionTarget, SEL completionSelector, void *contextInfo); 保存完成后&#xff0c;会调用 comple…

微信小程序实时聊天之WebSocket

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文&#xff1a; 1.所有监听事件先在onload监听。 // pages/index/to_news/to_news.js var app getApp(); var socketOpen false; var SocketTask false; var url ws://192.168.0.120:7011; Page…

webform repeater

repeater:由模板构成&#xff0c;解析后模板就不存在了 需要指定数据源进行数据绑定 List<Fruit> list new FruitDA().Select(); // 数据查询 &#xff08;随便查寻的&#xff09; Repeater1.DataSource list; // 赋值 Repeater1…

远程协助软件开发_这是我从事远程软件开发人员工作的主要技巧

远程协助软件开发by Colin Morgan通过科林摩根(Colin Morgan) 这是我从事远程软件开发人员工作的主要技巧 (Here are the top tips I’ve used to land a remote software developer job) Applying for a remote software developer job means you are voluntarily choosing t…

简谈-Python一些常用的爬虫技巧

第一种&#xff1a;基本的网页抓取 get方法 import urllib2url "链接response urllib2.urlopen(url)print response.read() post方法 import urllibimport urllib2url "链接form {name:abc,password:1234}form_data urllib.urlencode(form)request urllib2.Req…

微信小程序画布圆形进度条demo

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文&#xff1a; wxml <!--pages/test/test.wxml--> <canvas style"width: 300px; height: 200px;" canvas-id"canvasid"></canvas>js // pages/test/test.js …

smarty 模板引擎

http://blog.csdn.net/zuiaituantuan/article/details/5951242 http://wenku.baidu.com/link?url-UHlSnTXOOAjFG1KjX6T9sEG6V4hNAMfRDpMuRRnc_FKbFAxiE5Ntk4lzxSm-7Z531uWdfvgYx81sdC61SgTZm7q8FdUt3gSs7ZlC0JR1SW转载于:https://www.cnblogs.com/hxjbc/p/4441879.html