iOS 单例模式 (设计模式一)

单例模式是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例类的特殊类。通过单例模式可以保证系统中一个类只有一个实例而且该实例易于外界访问,从而方便对实例个数的控制并节约系统资源。如果希望在系统中某个类的对象只能存在一个,单例模式是最好的解决方案。

主要优点:

主要缺点:

给HSCommonTool类设定单例模式: NSObject+ (instancetype)sharedCommonTool;@end()<// 定义一个静态变量static HSCommonTool *_commonTool;// 重写allocWithZone方法,alloc内部调用次方法+ (instancetype)allocWithZone:(struct _NSZone *)zone{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; \}

我们人生中最大的懒惰,就是当我们明知自己拥有作出选择的能力,

iOS 单例模式 (设计模式一)

相关文章:

你感兴趣的文章:

标签云: