iOS开发-单例模式

https://developer.apple.com/library/content/documentation/General/Conceptual/DevPedia-CocoaCore/Singleton.html

A singleton class returns the same instance no matter how many times an application requests it. A typical class permits callers to create as many instances of the class as they want, whereas with a singleton class, there can be only one instance of the class per process. A singleton object provides a global point of access to the resources of its class. Singletons are used in situations where this single point of control is desirable, such as with classes that offer some general service or resource.

一个使用单例实现的类,无论应用初始化了多少次,返回的仍是同一个对象。一个普通实现的类允许调用者任意创建若干个对象,且每个对象都是不同的。单例对象提供了在进程中唯一的方位对应的类的入口。单例一般在需要单点控制的时候使用,利用提供一些通用的服务和资源。

这里写图片描述

You obtain the global instance from a singleton class through a factory method. The class lazily creates its sole instance the first time it is requested and thereafter ensures that no other instance can be created. A singleton class also prevents callers from copying, retaining, or releasing the instance. You may create your own singleton classes if you find the need for them. For example, if you have a class that provides sounds to other objects in an application, you might make it a singleton. Several Cocoa framework classes are singletons. They include NSFileManager, NSWorkspace, and, in UIKit, UIApplication and UIAccelerometer. The name of the factory method returning the singleton instance has, by convention, the form sharedClassType. Examples from the Cocoa frameworks are sharedFileManager, sharedColorPanel, and sharedWorkspace.

您可以通过工厂方法从单例类获取全局实例。此类在第一次初始化的时候使用懒加载的方式创建它的唯一实例,并确保此后不会在创建其他实例。单例类还可以防止调用者复制,保留或释放实例。如果需要的话,你可以创建自己的单例。例如,在应用中你需要一个向其他对象提供声音的类 ,则可以将其设置为一个单例。 许多Cocoa框架类都是单例模式。例如NSFileManager,NSWorkspace和UIKit中的UIApplication和UIAccelerometer。按照惯例,返回单例实例的工厂方法的名称的格式为sharedClassType。 Cocoa框架的例子是sharedFileManager,sharedColorPanel和sharedWorkspace。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值