zoukankan      html  css  js  c++  java
  • iOS中的单例模式

    ARC


    懒汉模式

    #import "Singleton.h"
    
    @implementation Singleton
    static id _instance;
    
    /**
     *  alloc方法内部会调用这个方法
     */
    + (instancetype)allocWithZone:(struct _NSZone *)zone{
        if (_instance == nil) { // 防止频繁加锁
            @synchronized(self) {
                if (_instance == nil) { // 防止创建多次
                    _instance = [super allocWithZone:zone];
                }
            }
        }
        return _instance;
    }
    
    + (instancetype)sharedSingleton{
        if (_instance == nil) { // 防止频繁加锁
            @synchronized(self) {
                if (_instance == nil) { // 防止创建多次
                    _instance = [[self alloc] init];
                }
            }
        }
        return _instance;
    }
    
    - (id)copyWithZone:(NSZone *)zone{
        return _instance;
    }
    @end

    饿汉模式(不常用)

    #import "HMSingleton.h"
    
    @implementation Singleton
    static id _instance;
    
    /**
     *  当类加载到OC运行时环境中(内存),就会调用一次(一个类只会加载1次)
     */
    + (void)load{
        _instance = [[self alloc] init];
    }
    
    + (instancetype)allocWithZone:(struct _NSZone *)zone{
        if (_instance == nil) { // 防止创建多次
            _instance = [super allocWithZone:zone];
        }
        return _instance;
    }
    
    + (instancetype)sharedSingleton{
        return _instance;
    }
    
    - (id)copyWithZone:(NSZone *)zone{
        return _instance;
    }
    @end

    GCD实现单例模式

     
    @implementation Singleton
    static id _instance;
    
    + (instancetype)allocWithZone:(struct _NSZone *)zone{
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            _instance = [super allocWithZone:zone];
        });
        return _instance;
    }
    
    + (instancetype)sharedSingleton{
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            _instance = [[self alloc] init];
        });
        return _instance;
    }
    
    - (id)copyWithZone:(NSZone *)zone{
        return _instance;
    }
    @end

  • 相关阅读:
    翻转单词顺序列
    和为S的两个数字
    单例模式
    python利用pyinstaller打包常用打包命令
    python 3.8 使用pymssql 向SQL Server插入数据不成功原因
    PyQt5(designer)入门教程
    PyQt5中文教程
    scrapy 图片爬取 多层多页 保存不同的文件夹 重命名full文件夹
    安装Python + PyCharm + PyQt5配套设置
    python用pymysql模块操作数据库MySQL,实现查增删改
  • 原文地址:https://www.cnblogs.com/wanghuaijun/p/5586389.html
Copyright © 2011-2022 走看看