设计模式之 Singleton 单例模式:Swift 实现

本文详细介绍了Singleton模式的作用,包括确保类的唯一实例和提供全局访问。通过实例化过程和饿汉模式、懒汉模式的对比,深入剖析了其实现方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Singleton 单例模式

Singleton can solve two problem:

  • Keep that one specific class have only one instance

  • Provide a global access node for this instance

    Implementation:

  • Set the default initializer as private to prevent other objects use it.

  • Create a static func that will call the default initializer if the single instance is null, then this class will have this only one instance.

单例模式解决了可以解决两个问题:

  • 保证某个类只有一个实例
  • 为这个实例提供全局的访问节点

实现:

  • 将默认的构造函数设置为私有,让其它对象无法访问。

  • 新建一个静态函数,在这个函数内进行判断,若单例对象为空,则调用私有的构造函数来创建实例对象,实例只被创建一次。

    在这里插入图片描述

class FileAccess {
    private static var obj: FileAccess? = nil
    private init(){
        
    }
    public static func getInstance() {
        if obj == nil {
            obj = FileAccess()
        }
    }
}

let firstAccess = FileAccess.getInstance()

let secondAccess = FileAccess.getInstance()

// These two access are reference to a same instance.

单例模式有两种形式:

  • 饿汉模式
    表示很饥饿,在程序启动预加载的时候就生成单个实例。
  • 懒汉模式
    表示很懒惰,在程序启动预加载的时候不生成实例,当需第一次访问这个实例的时候再生成这个实例。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值