单例

作者: 6灰太狼9 | 来源:发表于2017-03-30 15:53 被阅读5次

单例的作用和功能这里不想在多说,相信大家都已经比较了解,这里直接写单利类.m文件中的代码(适配了arc和mrc)

@interface HTUser : NSObject+ (instancetype)shareHTUser;

@end

@implementation HTUser

static HTUser *_instance;  //这里static表示_instance这个变量只能在该类中使用。

+(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;

}

+ (instancetype)shareHTUser{

//最好写成self  加入是类型  则这个类的子类无法使用

return [[self alloc] init];

}

-(id)copyWithZone:(NSZone *)zone{

return _instance;

}

- (id)mutableCopyWithZone:(NSZone *)zone{

return _instance;

}

#if __has_feature(objc_arc)

//arc

#else

//mrc

-(oneway void)release{

}

-(instancetype)retain{

return _instance;

}

-(NSUInteger)retainCount{

return MAXFLOAT;  //返回最大值 让其他人知道这个类是单利

}

#endif

@end

因为单例的代码大多数代码是一样的,所以单例的代码也可以用宏来表示

#define singleH(name) + (instancetype)share##name;

#if __has_feature(objc_arc)

#define singleM(name) static id _instance;\

+(instancetype)allocWithZone:(struct _NSZone *)zone{\

static dispatch_once_t onceToken;\

dispatch_once(&onceToken, ^{\

_instance = [super allocWithZone:zone];\

});\

return _instance;\

}\

+ (instancetype)share##name{\

return [[self alloc] init];\

}\

-(id)copyWithZone:(NSZone *)zone{\

return _instance;\

}\

- (id)mutableCopyWithZone:(NSZone *)zone{\

return _instance;\

}

#else

#define singleM(name) static id _instance;\

+(instancetype)allocWithZone:(struct _NSZone *)zone{\

static dispatch_once_t onceToken;\

dispatch_once(&onceToken, ^{\

_instance = [super allocWithZone:zone];\

});\

return _instance;\

}\

+ (instancetype)share##name{\

return [[self alloc] init];\

}\

-(id)copyWithZone:(NSZone *)zone{\

return _instance;\

}\

- (id)mutableCopyWithZone:(NSZone *)zone{\

return _instance;\

}\

-(oneway void)release{\

}\

-(instancetype)retain{\

return _instance;\

}\

-(NSUInteger)retainCount{\

return MAXFLOAT;\

}

#endif

相关文章

  • Android设计模式总结

    单例模式:饿汉单例模式://饿汉单例模式 懒汉单例模式: Double CheckLock(DCL)实现单例 Bu...

  • IOS单例模式的底层原理

    单例介绍 本文源码下载地址 1.什么是单例 说到单例首先要提到单例模式,因为单例模式是单例存在的目的 单例模式是一...

  • 【设计模式】单例模式

    单例模式 常用单例模式: 懒汉单例模式: 静态内部类单例模式: Android Application 中使用单例模式:

  • 2020-11-02-Spring单例 vs. 单例模式

    Spring 单例不是 Java 单例。本文讨论 Spring 的单例与单例模式的区别。 前言 单例是 Sprin...

  • IOS学习笔记之单例

    单例介绍 1.什么是单例 说到单例首先要提到单例模式,因为单例模式是单例存在的目的 单例模式是一种常用的软件设计模...

  • OC - 单例模式

    导读: 一、什么是单例模式 二、单例的作用 三、常见的单例类 四、自定义单例类的方法 一、什么是单例模式 单例模式...

  • 单例

    单例 单例宏

  • 单例模式

    特点 单例类只有1个实例对象 该单例对象必须由单例类自行创建 单例类对外提供一个访问该单例的全局访问点 结构 单例...

  • 关于java单例模式,这篇已经讲得很清楚了,建议收藏!

    概念 java中单例模式是一种常见的设计模式,单例模式分三种:懒汉式单例、饿汉式单例、登记式单例三种。 特点 单例...

  • 单例

    iOS单例模式iOS之单例模式初探iOS单例详解

网友评论

      本文标题:单例

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