返回 导航

Swift

hangge.com

Swift - 单例模式的实现

作者:hangge | 2015-07-28 09:11
过去 Swift 要实现单例,无非是这三种方式:全局变量,内部变量和 dispatch_once 方式。但都略显繁琐。
后来从 1.2 版本起,Swift 中添加了如 static letstatic var 这样的类变量的支持,这样单例的实现又简化了许多。

下面提供两种比较好的单例写法。(要注意:不管哪种写法都要注意将 init() 方法私有化。因为在 Swift 中,所有对象的构造器默认都是 public,需要重写 init 让其成为私有的,防止其他对象使用这个类的默认的'()'初始化方法来创建对象。这里感谢网友nowIsFuture的提醒。)

方法1:
class AppManager {
    private static let _sharedInstance = AppManager()
    
    class func getSharedInstance() -> AppManager {
        return _sharedInstance
    }
    
    private init() {} // 私有化init方法
}

//使用方式
AppManager.getSharedInstance()

方法2:
class AppManager {
    static let sharedInstance = AppManager()
    
    private init() {} // 私有化init方法
}

//使用方式
AppManager.sharedInstance

附一:为什么需要保证INIT的私有化? 

因为只有 init() 是私有的,才能防止其他对象通过默认构造函数直接创建这个类对象,确保你的单例是真正的独一无二。 
因为在 Swift 中,所有对象的构造器默认都是 public,所以需要重写你的 init 让其成为私有的。这样就保证像如下的代码编译报错,不能通过。
var a1 = AppManager() //确保编译不通过
var a2 = AppManager() //确保编译不通过

附二:如何将单例对象置为nil?

有时我们可能需要将单例对象设为 nil,或重新创建一个新的实例。我们可以使用如下代码实现:
class AppManager {
    private static var _sharedInstance: AppManager?
    
    class func getSharedInstance() -> AppManager {
        guard let instance = _sharedInstance else {
            _sharedInstance = AppManager()
            return _sharedInstance!
        }
        return instance
    }
    
    private init() {} // 私有化init方法
    
    //销毁单例对象
    class func destroy() {
        _sharedInstance = nil
    }
}

//使用方式
AppManager.getSharedInstance()
AppManager.destroy()
评论

全部评论(4)

回到顶部