zoukankan      html  css  js  c++  java
  • Swift_单例的打开方式

    谈到单例,我们要想到几点:为什么使用单例,单例实现原理是什么,使用过程中有哪些问题是需要注意的?

    单例作为一种设计模式,也更是一种解决方案。

    >>>>>>>为什么使用单例:

    1、资源共享的情况下,避免资源操作时导致的性能或损耗。

    2、控制自已的情况下,方便资源之间的互相通信。

    >>>>>>>单例的规则:

    1、单例必须是在程序生命周期中只能存在一个的实例,并且可以全局访问这个单例。(NSNotificationCenter,UIApplication)

    2、单例类的初始化方法必须是私有化,这样可以避免其他对象通过单例类创建额外的实例化单例类变量。

    3、为保证在整个程序的生命周期中只有一个实例被创建,单例必须保证线程安全。如果有两个线程同时实例化一个单例对象,就可能会创建两个单例对象。所以,只有保证线程安全,才能保证单例的唯一性。通过调用dispatch_once,可保证实例化代码只运行一次。

    >>>>>>>单例实现方法:

    方法一:只是语法转换到了swfit,跟OC实现方式一样

     class TLOncePatch {
        
        var tlOncePatch : TLOncePatch?
        
        class func shareInstance() -> TLOncePatch{
            
            struct single {
                static var predicate : dispatch_once_t = 0
                static var instance : TLOncePatch? = nil
            }
            
            dispatch_once(&single.predicate) {
                single.instance = TLOncePatch()
            }
            
            return single.instance!
        }
        
        private init(){       
        }
    }

    方法二:结构体方法

    class TLThirdOnce{
        
        var tValue = "df"
        
        class var shareOnce : TLThirdOnce {
            struct tOnce {
                static let instance = TLThirdOnce()
            }
            return tOnce.instance
        }
    }

     

    方法三:全局变量方法

    private let forthOnce = TLForthOnce()
    class TLForthOnce{
        class var tOnce : TLForthOnce{
            return forthOnce
        }
    }

    方法四:单行例模式

    class TLFifthOnce{
        static let tlOnce = TLFifthOnce()
        private init(){}
    }

  • 相关阅读:
    hdu4639 hehe ——斐波纳契数列,找规律
    codefoces round193a
    codeforces 192e
    abbyy cup a
    年中总结
    codeforces 192a
    codeforces 192b
    codeforces 192 c
    codeforces 192 D
    codeforces magic five --快速幂模
  • 原文地址:https://www.cnblogs.com/madarax/p/6101418.html
Copyright © 2011-2022 走看看