栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

斯威夫特的辛格尔顿

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

斯威夫特的辛格尔顿

标准的单例模式为:

final class Manager {    static let shared = Manager()    private init() { ... }    func foo() { ... }}

您将像这样使用它:

Manager.shared.foo()

感谢appzYourLife指出应该声明它

final
以确保它不会被意外子类化,以及
private
对初始值设定项使用access修饰符,以确保您不会意外地实例化另一个实例。

因此,回到图像缓存问题,您将使用以下单例模式:

final class ImageCache {    static let shared = ImageCache()    /// Private image cache.    private var cache = [String: UIImage]()    // Note, this is `private` to avoid subclassing this; singletons shouldn't be subclassed.    private init() { }    /// Subscript operator to retrieve and update cache    subscript(key: String) -> UIImage? {        get { return cache[key]        }        set (newValue) { cache[key] = newValue        }    }}

那么你就可以:

ImageCache.shared["photo1"] = imagelet image2 = ImageCache.shared["photo2"])

要么

let cache = ImageCache.sharedcache["photo1"] = imagelet image2 = cache["photo2"]

上面显示了简单的单例缓存实现后,我们应该注意,您可能想要(a)通过使用使其线程安全

NSCache
;(b)应对记忆压力。因此,实际的实现类似于Swift
3中的以下内容:

final class ImageCache: NSCache<AnyObject, UIImage> {    static let shared = ImageCache()    /// Observer for `UIApplicationDidReceiveMemoryWarningNotification`.    private var memoryWarningObserver: NSObjectProtocol!    /// Note, this is `private` to avoid subclassing this; singletons shouldn't be subclassed.    ///    /// Add observer to purge cache upon memory pressure.    private override init() {        super.init()        memoryWarningObserver = NotificationCenter.default.addObserver(forName: .UIApplicationDidReceiveMemoryWarning, object: nil, queue: nil) { [weak self] notification in self?.removeAllObjects()        }    }    /// The singleton will never be deallocated, but as a matter of defensive programming (in case this is    /// later refactored to not be a singleton), let's remove the observer if deallocated.    deinit {        NotificationCenter.default.removeObserver(memoryWarningObserver)    }    /// Subscript operation to retrieve and update    subscript(key: String) -> UIImage? {        get { return object(forKey: key as AnyObject)        }        set (newValue) { if let object = newValue {     setObject(object, forKey: key as AnyObject) } else {     removeObject(forKey: key as AnyObject) }        }    }}

您将按以下方式使用它:

ImageCache.shared["foo"] = image

let image = ImageCache.shared["foo"]


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/409660.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号