zoukankan      html  css  js  c++  java
  • swift语言实现单例模式


    Swift实现单例模式

    单例模式在各个语言中都有实现,swift语言推出已经几天了。通过这几天的看文档。特奉上写的Swift的单例实现,供大家学习交流,欢迎指正。


    ---若转载请注明出处,本人Github博客新地址- YueRuo's Blog - http://yueruo.github.io ---


    因为Swift语言弱化了struct和class之间的界限,这里我分别给出自己写的两种的单例实现

    class版本号:
    class SwiftSingleton{
        class func shareInstance()->SwiftSingleton{
            struct YRSingleton{
                static var predicate:dispatch_once_t = 0
                static var instance:SwiftSingleton?

    = nil } dispatch_once(&YRSingleton.predicate,{ YRSingleton.instance=SwiftSingleton() } ) return YRSingleton.instance! } }

    对于单例类。须要一个唯一的对外输出实例的shareInstance方法。而通过官方文档的查阅,发现对于class来说。静态方法能够用class func 来标示。静态变量使用class var来处理,但这里我借助了内部struct的静态变量来对唯一的instance进行存储。

    调用时,能够使用

    var swiftInstance1=SwiftSingleton.shareInstance()
    var swiftInstance2=SwiftSingleton.shareInstance()
    if swiftInstance1===swiftInstance2{//“===”判别是否是同一个实例对象
        println("they are the same instance!")
    }
    

    另外,上面使用到了dispatch_once,有过GCD编程经验的应该会很熟悉,能够保证线程安全,以及仅仅会被调用一次。



    struct版本号

    struct版本号与class版本号差点儿一致,唯一差别在于对于func使用的keyword由class func变为 static func

    struct StructSingleton{
        static func shareInstance()->StructSingleton{
            struct YRSingleton{
                static var predicate:dispatch_once_t = 0
                static var instance:StructSingleton?

    = nil } dispatch_once(&YRSingleton.predicate,{ YRSingleton.instance=StructSingleton() } ) return YRSingleton.instance! } }

  • 相关阅读:
    heapq of python
    array of python
    Unittest of Python
    事件驱动型工作流 vs 引擎型工作流
    airflow
    WPF 调试触发器
    WPF 使用Popup和TreeView实现树状下拉框
    Oracle : ORA 00933: SQL command not properly ended
    PostgreSQL && PostGIS
    基于ArcGIS开发3D立方体空间关系判断
  • 原文地址:https://www.cnblogs.com/cxchanpin/p/6746773.html
Copyright © 2011-2022 走看看