开发模式——单例模式

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

利用双重检查来实现单例

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
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容