iOS单例模式

单例模式大概是设计模式种较简单的一种设计模式。但在实际的开发过程中仍然存在一些坑。所以本文总结了下iOS中的单例模式。

什么是单例模式?

  • ensures a class only has one instance
  • provides a global point of access to it
  • 确保一个类永远只有一个实例
  • 提供一个全局的访问入口访问这个实例

苹果官方文档的一副图描述了请求普通类和单例的区别:


请求普通类与单例的区别

如何实现基本的单例模式?

Singleton *sharedInstance = nil;

+ (instancetype)sharedIntance {
    if (sharedInstance == nil) {
        sharedInstance = [[Singleton alloc] init];
    }
    
    return sharedInstance;
}

全局的变量sharedInstance有个缺点,可以被外部随意修改,为了隔离外部修改,可以设置成局部静态变量。

+ (instancetype)sharedInstance {
    static Singleton *sharedInstance = nil;
    if (sharedInstance == nil) {
        sharedInstance = [[Singleton alloc] init];
    }
    
    return sharedInstance;
}

单例的核心思想就算实现了。

多线程如何处理?

上述例子虽然实现了单例的核心思想,但依然存在问题。在多线程情况下即多个线程同时访问sharedInstance工厂方法,并不能保证只创建一个实例对象。

那么,如何保证在多线程的下依旧能够只创建一个实例对象呢?iOS下我们可以使用NSLock@synchronized等多种线程同步技术。

+ (instancetype)sharedInstance {
    static Singleton *sharedInstance = nil;
    @synchronized (self) {
        if (sharedInstance == nil) {
            sharedInstance = [[Singleton alloc] init];
        }
    }

    return sharedInstance;
}

@synchronized虽然保证了在多线程下调用sharedInstance工厂方法只会创建一个实例对象,但是@synchronized的性能较差。OC内部提供了一种更加高效的方式,那就是dispatch_once@synchronized性能相较于dispatch_once要差几倍,甚至几十倍。关于二者的性能对比,请参考这里

+ (instancetype)sharedInstance {
    static Singleton *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[Singleton alloc] init];
    });

    return sharedInstance;
}

Objective-C中实现单例存在的坑

上述实现单例的方式看起来很完美了。虽然我们提供了一个方便的工厂方法返回单例,但是用户依然能够调用alloc方法创建对象。这样外部使用的时候依旧能够创建多个实例。解决上述问题有两种方案:

1. 技术上实现无论怎么调用都返回同一个单例对象

To create a singleton as the sole allowable instance of a class in the current process. This code does the following:

  • It declares a static instance of your singleton object and initializes it to nil.
  • In your class factory method for the class (named something like “sharedInstance” or “sharedManager”), it generates an instance of the class but only if the static instance is nil.
  • It overrides the allocWithZone: method to ensure that another instance is not allocated if someone tries to allocate and initialize an instance of your class directly instead of using the class factory method. Instead, it just returns the shared object.
  • It implements the base protocol methods copyWithZone:, release, retain, retainCount, and autorelease to do the appropriate things to ensure singleton status. (The last four of these methods apply to memory-managed code, not to garbage-collected code.)
+ (instancetype)sharedInstance {
    static Singleton *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[super allocWithZone:NULL] init];
    });

    return sharedInstance;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    return [self sharedInstance];
}

- (id)copy {
    return [Singleton sharedInstance];
}

- (id)mutableCopy {
    return [Singleton sharedInstance];
}

如下图所示,不管使用何种方式创建对象都返回相同的实例对象。


实例变量的地址

2.利用编译器特性给用户提示,但不强制约束

利用编译器特性直接告诉外部newalloccopymutableCopy方法不能直接调用,否则编译不通过。

+ (instancetype)sharedInstance;

+ (instancetype)new OBJC_UNAVAILABLE("use sharedInstance instead.");
+ (instancetype)alloc OBJC_UNAVAILABLE("use sharedInstance instead.");
- (id)copy OBJC_UNAVAILABLE("use sharedInstance instead.");
- (id)mutableCopy OBJC_UNAVAILABLE("use sharedInstance instead.");

若直接调用alloc等方法创建对象,编译器则会给出错误提示:

编译器错误提示

单例模式潜在的问题

  • 内存问题
    单例模式实际上是延长了对象的生命周期,那么就存在内存的问题,因为单例对象在程序的整个生命周期里都存在,直到程序退出才会释放。

参考文献:
Singleton
Creating a Singleton Instance

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335

推荐阅读更多精彩内容

  • 单例模式的意思就是只有一个实例。单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。这个类称...
    Asserts阅读 358评论 0 1
  • 前言单例模式基本上是最简单的设计模式,它使类的一个对象成为整个系统的唯一实例。 基础款 基本上是最简单的单例创建形...
    madaoCN阅读 1,519评论 3 7
  • iOS设计模式——单例模式http://blog.csdn.net/lovefqing/article/detai...
    LV大树阅读 706评论 0 1
  • 什么是单例 ? 单例模式是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例类的特殊类。通过单例模式可以...
    milk_powder阅读 1,942评论 0 0
  • 简介: 单例模式是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例类的特殊类。通过单例模式可以保证系统...
    RunnerFL阅读 628评论 0 0