博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
关于单例设计模式
阅读量:4469 次
发布时间:2019-06-08

本文共 1260 字,大约阅读时间需要 4 分钟。

在ios开发中,很多时候我们会需要用到单例,一般我们会用到两种实现单例的方式。第一种是:

第二种是:

针对这两个方法,我们提出两点疑问:

1.为什么必须用static修饰符?

2.这两种方法有什么区别?

我们先来回答第一个问题。static修饰符在这里的作用就是把变量分配在静态存储区,并且只会分配一次内存,无论你调用多少次这个方法,被static修饰的变量就是它第一次分配的那个,它的生命周期是从应用程序开始到应用程序结束。这样就保证了这个单例对象的唯一性。如果我们不用static修饰符,那么每次调用这个单例方法的时候,系统每次都会在栈上分配一个变量,这样生成的实例就不唯一了。

这两种生成单例的方法的区别是方法一不是线程安全的,在多线程的环境下可能有多个线程同时调用了方法一,造成生成不同的实例,而方法二是线程安全的,这附上苹果官方文档的解释:

dispatch_once

Executes a block object once and only once for the lifetime of an application.
Declaration

void dispatch_once( dispatch_once_t *predicate, dispatch_block_t block);

Parameters

predicate:A pointer to a dispatch_once_t structure that is used to test whether the block has completed or not.

block:The block object to execute once.

This function is useful for initialization of global data (singletons) in an application. Always call this function before using or testing any variables that are initialized by the block.If called simultaneously from multiple threads, this function waits synchronously until the block has completed.The predicate must point to a variable stored in global or static scope. The result of using a predicate with automatic or dynamic storage (including Objective-C instance variables) is undefined.

 

转载于:https://www.cnblogs.com/qmmq/p/5279567.html

你可能感兴趣的文章
IIS服务中五种身份验证
查看>>
c#网络编程-第一章
查看>>
paip.提升效率--僵尸代码的迷思
查看>>
Atitit 自动化gui 与 发帖机 技术
查看>>
Atitit.研发团队与公司绩效管理的原理概论的attilax总结
查看>>
编程模式之装饰模式(Decorator)
查看>>
MVC中关于 使用后台代码 检查 用户名是否已经被清册
查看>>
匿名函数
查看>>
nginx相关
查看>>
(各个公司面试原题)在线做了一套CC++综合測试题,也来測一下你的水平吧(二)...
查看>>
多种选择(Switch)
查看>>
[设计模式] .NET设计模式笔记 - 有多少种设计模式
查看>>
笔记52 Mybatis快速入门(三)
查看>>
Cracking The Coding Interview 1.2
查看>>
PL/SQL报错:无法解析指定的连接标识符
查看>>
LAMP安全加固
查看>>
力扣 5063 最后一块石头的重量 & II
查看>>
导航狗信息导航网站首页源代码(2017年11月03日版)
查看>>
Java中的Class.forName
查看>>
20165223 实验五 网络编程与安全
查看>>