单例模式

一、介绍

介绍

二、单例模式代码实现

//创建一个类XMGTool,实现单例
--------------------------XMGTool.h文件--------------------------
#import <Foundation/Foundation.h>

@interface XMGTool : NSObject<NSCopying,NSMutableCopying>

//提供类方法,方便外界访问
/*
 规范:share + 类名 |share |default + 类名
 */

+(instancetype)shareTool;
@end
--------------------------XMGTool.m文件--------------------------
#import "XMGTool.h"

@implementation XMGTool

//01 提供一个全局的静态变量(对外界隐藏)
static XMGTool *_instance;

//02 重写alloc方法,保证永远只分配一次内存
// alloc - > allocWithZone(分配存储空间)

+(instancetype)allocWithZone:(struct _NSZone *)zone{
    /*
    @synchronized(self) {
        if (_instance == nil) {
            _instance = [super allocWithZone:zone];
        }
    }
     */
    
    //在程序运行过程中只执行一次+线程安全
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone];
    });
    
    return _instance;
}

//03 提供类方法
+(instancetype)shareTool
{
    return [[self alloc]init];
}

//04 重写copy,对象方法,首先要创建对象
-(id)copyWithZone:(NSZone *)zone
{
    return _instance;
}

-(id)mutableCopyWithZone:(NSZone *)zone
{
    return _instance;
}

@end
----------------------------在外界调用--------------------------
- (void)viewDidLoad {
    [super viewDidLoad];

    //创建对象
    XMGTool *t1 = [[XMGTool alloc]init];
    
    XMGTool *t2 = [[XMGTool alloc]init];
    XMGTool *t3 = [XMGTool new];
    
    NSLog(@"\n%@\n%@\n%@\n%@\n%@",t1,t2,t3,[XMGTool shareTool],[t1 copy]);
    
}

三、单例的简介写法

//此方法中缺点,不能使用alloc init 或者copy.mutableCopy方法创建对象
-------------------------------XMGTool.h方法---------------------------
#import <Foundation/Foundation.h>

@interface XMGTool : NSObject

+(instancetype)shareTool;
@end
-------------------------------XMGTool.m方法---------------------------
#import "XMGTool.h"

@implementation XMGTool

+(instancetype)shareTool
{
    //01 提供静态变量
    static XMGTool * _instance;
    
    //02 一次性代码
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [self new];
    });
    
    return _instance;
}
@end
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容