通过示例分析Swift单例模式
三种Swift实现单例模式的方法:全局变量,内部变量,dispatch_once方式
1.全局变量
privatelet_singleton=Singleton()
classSingleton:NSObject{
classvarsharedInstance:Singleton{
get{
return_singleton
}
}
}
2.内部变量
classSingleton{
classvarsharedInstance:Singleton{
get{
structSingletonStruct{
staticletsingleton:Singleton=Singleton()
}
returnSingletonStruct.singleton
}
}
}
3.dispatch_once方式
classSingleton{
classvarsharedInstance:Singleton{
get{
structSingletonStruct{
staticvaronceToken:dispatch_once_t=0
staticvarsingleton:Singleton?=nil
}
dispatch_once(&SingletonStruct.onceToken,{()->Voidin
SingletonStruct.singleton=Singleton()
})
returnSingletonStruct.singleton!
}
}
}
以上所述就是本文的全部内容了,希望大家能够喜欢。
热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短