单例设计模式

单例设计模式

  • 单例设计模式:让类的对象称为系统中唯一的实例
  • 想要实现单例的类,必须遵守NSCopying和NSMutableCopying协议
  • 重写allocWithZone:方法
  • 重写copyWithZone:方法
  • 重写mutableCopyWithZone:方法
  • 提供访问单例的方法shareSoundTool
  • MRC还需要重写其他的方法
static SoundTool *_instance = nil;
+ (instancetype)shareSoundTool
{
    SoundTool *instance = [[self alloc] init];
    return instance;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[super allocWithZone:zone] init];
    });
    return _instance;
}


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

    return _instance;
}

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

// MRC
#if !__has_feature(objc_arc)
- (oneway void)release
{
}

- (instancetype)retain
{
    return _instance;
}

- (NSUInteger)retainCount
{
    return  MAXFLOAT;
}
 
- (instancetype)autorelease
{
    return self;
}
#endif

单例可以定义成宏

// .h文件中方法声明
#define interfaceSingleton(name)  +(instancetype)share##name

// .m文件中方法实现
#if __has_feature(objc_arc)
// ARC
#define implementationSingleton(name)  \
static name *_instance = nil; \
+ (instancetype)share##name \
{ \
    name *instance = [[self alloc] init]; \
    return instance; \
} \
+ (instancetype)allocWithZone:(struct _NSZone *)zone \
{ \
    static dispatch_once_t onceToken; \
    dispatch_once(&onceToken, ^{ \
        _instance = [[super allocWithZone:zone] init]; \
    }); \
    return _instance; \
} \
- (id)copyWithZone:(NSZone *)zone{ \
    return _instance; \
} \
- (id)mutableCopyWithZone:(NSZone *)zone \
{ \
    return _instance; \
}
#else
// MRC

#define implementationSingleton(name)  \
static name *_instance = nil; \
+ (instancetype)share##name \
{ \
    name *instance = [[self alloc] init]; \
    return instance; \
} \
+ (instancetype)allocWithZone:(struct _NSZone *)zone \
{ \
    static dispatch_once_t onceToken; \
    dispatch_once(&onceToken, ^{ \
        _instance = [[super allocWithZone:zone] init]; \
    }); \
    return _instance; \
} \
- (id)copyWithZone:(NSZone *)zone{ \
    return _instance; \
} \
- (id)mutableCopyWithZone:(NSZone *)zone \
{ \
    return _instance; \
} \
- (oneway void)release \
{ \
} \
- (instancetype)retain \
{ \
    return _instance; \
} \
- (NSUInteger)retainCount \
{ \
    return  MAXFLOAT; \
}\
- (instancetype)autorelease\
{\
    return self;\
}
#endif
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 在iOS中有很多的设计模式,有一本书《Elements of Reusable Object-Oriented S...
    郑明明阅读 7,204评论 3 26
  • 什么是单例模式 单例模式就是要保证系统中一个类只有一个对象实例。无论用什么方法创建多少次,所得的对象都是同一个对象...
    acJohn阅读 3,624评论 0 0
  • 一.单例设计模式 1.单例模式:某一个类在所在应用程序中只有一个实例,将类的实例化限制成仅一个对象的设计模式。 2...
    懒眉阅读 1,778评论 0 0
  • 什么是单例模式? 单例模式是一种常用的软件设计模式。可以保证通过单例模式可以保证系统中一个类只有一个实例而且该实例...
    WakeMeUP1阅读 4,547评论 0 2
  • { 1.单例简介: 作用: 保证程序在运行过程中,一个类只有一个实例对象.这个实例对象容易被外界访问! 控制实例对...
    帥陽阅读 1,576评论 0 0

友情链接更多精彩内容