说明
单例设计模式,方便的地方在于保持状态。弊端也在这里,比如用户已经注销,需要重置跟用户相关的信息。
单例重置对象解决
class Singleton {
private static var privateShared: Singleton?
let date = Date()
class func shared() -> Singleton {
guard let unwrapShared = privateShared else {
privateShared = Singleton()
return privateShared!
}
return unwrapShared
}
class func destroy() {
privateShared = nil
}
func printDate() {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateString = formatter.string(from: date)
print("create Sigleton time > \(dateString)")
}
private init() {
print("init singletion")
}
deinit {
print("deinit singleton")
}
}
运用如下
Singleton.shared().printDate()
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2)) {
Singleton.shared().printDate()
}
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(4)) {
Singleton.destroy()
Singleton.shared().printDate()
}
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(6)) {
Singleton.shared().printDate()
}
打印结果
init singletion
create Sigleton time > 2020-04-09 09:16:26
create Sigleton time > 2020-04-09 09:16:26
deinit singleton
init singletion
create Sigleton time > 2020-04-09 09:16:30
create Sigleton time > 2020-04-09 09:16:30
参考
https://stackoverflow.com/questions/34046940/how-to-reset-singleton-instance
https://www.runoob.com/design-pattern/singleton-pattern.html