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。