zoukankan      html  css  js  c++  java
  • 单例-Singleton-01

    .h文件

    #import <Foundation/Foundation.h>
    
    @interface HMMusicTool : NSObject <NSCopying>
    @property (nonatomic, strong) NSMutableArray *musics;
    
    + (instancetype)shareTool;
    @end

    .m文件

    #import "HMMusicTool.h"
    @interface HMMusicTool ()
    @end;
    
    @implementation HMMusicTool
    // 全局变量
    // 用static修饰,能够保证_musicTool只能够被当前文件(.m)访问,其它外部文件不能访问
    static id _musicTool;
    
    - (NSMutableArray *)musics
    {
        if(!_musics)
        {
            _musics = [NSMutableArray array];
        }
        return _musics;
    }
    
    // alloc方法内部调用这个方法
    + (instancetype)allocWithZone:(struct _NSZone *)zone
    {
        if(!_musicTool){  // 防止频繁加锁
            // 加锁,线程安全
            @synchronized(self){ // 防止创建多次
                if(!_musicTool){
                    _musicTool = [super allocWithZone:zone];
                }
            }
        }
        return _musicTool;
    }
    
    + (instancetype)shareTool
    {
        if(!_musicTool){ // 防止频繁加锁
            @synchronized(self){
                if(!_musicTool) // 防止创建多次
                {
                    _musicTool = [[self alloc] init];
                }
            }
        }
        return _musicTool;
    }
    
    - (id)copyWithZone:(NSZone *)zone
    {
        return _musicTool;
    }
    @end
  • 相关阅读:
    10月日常练习1题目描述
    普及组复赛历年考题
    9.3练习题7 子串乘积正负分类 题解
    9.3练习题6 旅行 题解
    9.3练习题4 语句解析 题解
    9.3练习题5 单词覆盖还原 题解
    unity
    矩阵快速幂
    点权和
    SCOI生日快乐
  • 原文地址:https://www.cnblogs.com/fkunlam/p/4342345.html
Copyright © 2011-2022 走看看