当前位置:网站首页>单例模式:Swift 实现
单例模式:Swift 实现
2022-07-30 05:43:00 【大头鑫】
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.
单例模式有两种形式:
- 饿汉模式
表示很饥饿,在程序启动预加载的时候就生成单个实例。 - 懒汉模式
表示很懒惰,在程序启动预加载的时候不生成实例,当需第一次访问这个实例的时候再生成这个实例。
边栏推荐
猜你喜欢
Redis publish/subscribe
MySQL data types and footprint
TDengine cluster construction
Function 函数式接口及应用
Bypassing the file upload vulnerability
Blind injection, error injection, wide byte injection, stack injection study notes
mysql is not an internal or external command, nor is it a runnable program or batch file to resolve
c#下Web3合约空投、转账调用代码
Thread state of five
Usage of exists in sql
随机推荐
sql中 exists的用法
Arthas 命令解析(jvm/thread/stack/heapdump)
在不同的服务器上基于docker部署redis主从同步
JVM Learning (2) Garbage Collector
vulnhub-XXE ctf security question
Go简单实现协程池
Nacos配置中心用法详细介绍
十八、Kotlin进阶学习:1、挂起函数执行的顺序;2、使用 async 和 await 异步执行挂起函数;3、协程的调度器;4、父子协程;
MySQL - 函数及约束命令
MySQL window function
Flink PostgreSQL CDC configuration and FAQ
Remember a Mailpress plugin RCE vulnerability recurrence
十六、Kotlin进阶学习:协程详细学习。
FastAPI 快速入门
sql concat()函数
Shardingsphere depots table and configuration example
mysql delete duplicate data in the table, (retain only one row)
A Spark task tuning 】 【 one day suddenly slow down how to solve
GraphQL (1) Basic introduction and application examples
二十二、Kotlin进阶学习:简单学习RecyclerView实现列表展示;