
1. 单例设计模式(Singleton)
* 保证某个类创建出来的对象永远只有一个
2. 作用
* 节省内存开销。
* 如果有些数据,整个程序中都用得上,只需要使用同一份资源(保证大家访问的数据是相同一致的)
* 一般来说工具类设计为单例模式合适
3. 实现
* MRC
* ARC
SoundTool.h
1 #import <Foundation/Foundation.h> 2 3 @interface SoundTool : NSObject <NSCopying> 4 5 + (instancetype)shareSoundTool; 6 7 @endView Code
SoundTool.m
#import "SoundTool.h"
@implementation SoundTool
static id _instance = nil;
+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
if (_instance == nil) {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [super allocWithZone:zone];
});
}
return _instance;
}
+ (instancetype)shareSoundTool
{
return [[self alloc] init];
}
- (instancetype)init
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [super init];
});
return _instance;
}
+ (instancetype)copyWithZone:(struct _NSZone *)zone
{
return _instance;
}
+ (instancetype)mutableCopyWithZone:(struct _NSZone *)zone
{
return _instance;
}
//以下三个为非ARC使用
- (oneway void)release
{
}
- (instancetype)retain
{
return _instance;
}
- (NSUInteger)retainCount
{
return 1;
}
View Code
4. 建议包装成宏使用