标签:
单例模式是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例类的特殊类。通过单例模式可以保证系统中一个类只有一个实例而且该实例易于外界访问,从而方便对实例个数的控制并节约系统资源。如果希望在系统中某个类的对象只能存在一个,单例模式是最好的解决方案。
主要优点:
主要缺点:
给HSCommonTool类设定单例模式
#import <Foundation/Foundation.h>
@interface HSCommonTool : NSObject
+ (instancetype)sharedCommonTool;
@end
#import "HSCommonTool.h"
@interface HSCommonTool()<NSCopying>
@end
@implementation HSCommonTool
// 定义一个静态变量
static HSCommonTool *_commonTool;
// 重写allocWithZone方法,alloc内部调用次方法
+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
// 设定allocWithZone只执行一次
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_commonTool = [super allocWithZone:zone];
});
return _commonTool;
}
// copy对象时,调用此方法
- (id)copyWithZone:(nullable NSZone *)zone
{
return _commonTool;
}
// 写个类方法,方便外界调用
+ (instancetype)sharedCommonTool
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_commonTool = [[self alloc] init];
});
return _commonTool;
}
@end
单例模式的封装 - HSSingleton.h
// .h文件
#define HSGSingletonH(name) + (instancetype)shared##name;
// .m文件
#define HSGSingletonM(name) static id _instance; + (instancetype)allocWithZone:(struct _NSZone *)zone { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instance = [super allocWithZone:zone]; }); return _instance; } + (instancetype)shared##name { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instance = [[self alloc] init]; }); return _instance; } - (id)copyWithZone:(NSZone *)zone { return _instance; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/alincexiaohao/article/details/47070643