iOS 单例模式

作者: 风轻鱼蛋 | 来源:发表于2017-09-07 13:36 被阅读386次

    一、介绍

    iOS单例模式(Singleton)单例模式的意思就是只有一个实例。单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。这个类称为单例类。

    1、单例模式的要点:

    一是某个类只能有一个实例;
    二是它必须自行创建这个实例;
    三是它必须自行向整个系统提供这个实例。

    2、单例模式的优点:

    1.实例控制:Singleton 会阻止其他对象实例化其自己的 Singleton 对象的副本,从而确保所有对象都访问唯一实例。  
    2.灵活性:因为类控制了实例化过程,所以类可以更加灵活修改实例化过程 IOS中的单例模式

    二、实现单例

    单例模式写法:
    我们知道,创建对象的步骤分为申请内存(alloc)、初始化(init)这两个步骤,我们要确保对象的唯一性,因此在第一步这个阶段我们就要拦截它。
    当我们调用alloc方法时,oc内部会调用allocWithZone这个方法来申请内存,我们覆写这个方法,然后在这个方法中调用shareInstance方法返回单例对象,这样就可以达到我们的目的。
    拷贝对象也是同样的原理,覆写copyWithZone方法,然后在这个方法中调用shareInstance方法返回单例对象。

    static SLSingleton* _instance = nil;
    +(instancetype)shareInstance
    {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            _instance = [[super allocWithZone:NULL] init];
        });
        return _instance;
    }
    
    +(id)allocWithZone:(struct _NSZone *)zone
    {
        return [SLSingleton shareInstance];
    }
    
    -(id) copyWithZone:(struct _NSZone *)zone
    {
        return [SLSingleton shareInstance];
    }
    

    参考链接:
    IOS 单例设计模式解读
    Objective-c单例模式的正确写法

    相关文章

      网友评论

        本文标题:iOS 单例模式

        本文链接:https://www.haomeiwen.com/subject/ypfvjxtx.html