确保了一个类只有一个实例,并提供一个全局访问点。
利用双重检查来实现单例
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
}
}
网友评论