设计模式

开发模式——单例模式

2017-04-18  本文已影响12人  轻云绿原

确保了一个类只有一个实例,并提供一个全局访问点。

利用双重检查来实现单例

public class Singleton {

    private static volatile Singleton uniqueInstance;
    
    private Singleton () {}
    
    public static Singleton getInstance(){
        if (uniqueInstance == null) {
            synchronized (Singleton.class) {
                if (uniqueInstance == null) {
                    uniqueInstance = new Singleton();
                }
            }
        }
        return uniqueInstance;
    }
}
class Singleton{
    private static var uniqueInstance:Singleton!
    private static var lock = NSLock()
    private init() {}
    
    static var getInstance:Singleton{
        if uniqueInstance == nil{
            lock.lock()
            if uniqueInstance == nil {
                uniqueInstance = Singleton()
            }
            lock.unlock()
        }
        return uniqueInstance
    }
}
class Singleton{
    private static var uniqueInstance:Singleton!
    private init() {}
    
    static var getInstance:Singleton{
        if uniqueInstance == nil{
            objc_sync_enter(Singleton.self)
            if uniqueInstance == nil {
                uniqueInstance = Singleton()
            }
            objc_sync_exit(Singleton.self)
        }
        return uniqueInstance
    }
}
上一篇下一篇

猜你喜欢

热点阅读