Singleton 单例模式
Singleton can solve two problem:
-
Keep that one specific class have only one instance
-
Provide a global access node for this instance
Implementation:
-
Set the default initializer as private to prevent other objects use it.
-
Create a static func that will call the default initializer if the single instance is null, then this class will have this only one instance.
单例模式解决了可以解决两个问题:
- 保证某个类只有一个实例
- 为这个实例提供全局的访问节点
实现:
-
将默认的构造函数设置为私有,让其它对象无法访问。
-
新建一个静态函数,在这个函数内进行判断,若单例对象为空,则调用私有的构造函数来创建实例对象,实例只被创建一次。
class FileAccess {
private static var obj: FileAccess? = nil
private init(){
}
public static func getInstance() {
if obj == nil {
obj = FileAccess()
}
}
}
let firstAccess = FileAccess.getInstance()
let secondAccess = FileAccess.getInstance()
// These two access are reference to a same instance.
单例模式有两种形式:
- 饿汉模式
表示很饥饿,在程序启动预加载的时候就生成单个实例。 - 懒汉模式
表示很懒惰,在程序启动预加载的时候不生成实例,当需第一次访问这个实例的时候再生成这个实例。