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设计模式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值