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

9 篇文章 0 订阅

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() //确保编译不通过

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值