Swift-总结单例实现的几种方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chenglei9128/article/details/51151732

Swift实现代理的几种方法

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

3.

let _SharedInstance = AppManager()
class AppManager  {
   class var sharedInstance : AppManager {
    return _SharedInstance
   }
}
private init() {} // 私有化init方法
}
//使用方式
AppManager.sharedInstance

4.

class AppManager {
    class var sharedInstance : AppManager {
        struct Static {
            static let instance : AppManager = AppManager()
        }
        return Static.instance
    }
}
private init() {} // 私有化init方法
}
//使用方式
AppManager.sharedInstance

5.

class AppManager {
    class var sharedInstance : AppManager {
        struct Static {
            static var onceToken : dispatch_once_t = 0
            static var instance : AppManager? = nil
        }
        dispatch_once(&Static.onceToken) {
            Static.instance = AppManager()
        }
        return Static.instance!
    }
}
private init() {} // 私有化init方法
}
//使用方式
AppManager.sharedInstance

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

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

猜你喜欢

转载自blog.csdn.net/chenglei9128/article/details/51151732