版权声明:本文为博主原创文章,如若转载请注明博客来源以及地址,多谢 https://blog.csdn.net/xiaoluodecai/article/details/48416131
设计模式有许多中,如观察者模式,单例模式,工厂模式,门面模式,等等。
单例模式:
1.饿汉式:一进入程序就自动创建一个单例对象,但在移动端不是很适用;
2.懒汉式:当第一次使用到单例对象时,才创建对象;
懒汉式:(不使用GCD)
头文件中加入:
@interface HMDataTool : NSObject
+ (instancetype)sharedDataTool;
@end
在.m文件中:
#import "HMMusicTool.h"
@implementation HMMusicTool
static id _instance;//第一步,先定义一个全局静态id变量
/**
* alloc方法内部会调用这个方法
*/
+ (id)allocWithZone:(struct _NSZone *)zone
{
if (_instance == nil) { // 防止频繁加锁
@synchronized(self) {
if (_instance == nil) { // 防止创建多次
_instance = [super allocWithZone:zone];
}
}
}
return _instance;
}
+ (instancetype)sharedMusicTool
{
if (_instance == nil) { // 防止频繁加锁
@synchronized(self) {
if (_instance == nil) { // 防止创建多次
_instance = [[self alloc] init];
}
}
}
return _instance;
}
- (id)copyWithZone:(NSZone *)zone
{
return _instance;
}
@end
懒汉式(使用GCD)
#import "DataTool.h"
@implementation DataTool
static id _instance;
+(id)allocWithZone:(struct _NSZone *)zone
{
// if (_instance == nil) {
// @synchronized(self) {
// if (_instance == nil) {
// _instance = [[self alloc]init];
// }
// }
// }
//使用GCD,将上面的代码改成dispatch_once
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [[super allocWithZone:zone]init];
});
return _instance;
}
+(instancetype)shareDataTool
{
// if (_instance == nil) {
// @synchronized(self) {
// if (_instance == nil) {
// _instance = [[self alloc]init];
// }
// }
// }
//使用GCD,将上面的代码改成dispatch_once
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [[self alloc]init];
});
return _instance;
}
-(id)copyWithZone:(NSZone *)zone
{
return _instance;
}
@end
饿汉式的代码:
#import "HMSoundTool.h"
@implementation HMSoundTool
static id _instance;
/**
* 当类加载到OC运行时环境中(内存),就会调用一次(一个类只会加载1次)//饿汉式
*/
+ (void)load
{
_instance = [[self alloc] init];
}
//如果在load中装载,就不必要加锁,因为此时还没有线程
+ (id)allocWithZone:(struct _NSZone *)zone
{
if (_instance == nil) { // 防止创建多次
_instance = [super allocWithZone:zone];
}
return _instance;
}
+ (instancetype)sharedSoundTool
{
return _instance;
}
- (id)copyWithZone:(NSZone *)zone
{
return _instance;
}
///**
// * 当第一次使用这个类的时候才会调用
// */
//+ (void)initialize
//{
// NSLog(@"HMSoundTool---initialize");
//}
@end
非ARC模式:
代码:
#import "HMDataTool.h"
@implementation HMDataTool
// 用来保存唯一的单例对象
static id _instace;
+ (id)allocWithZone:(struct _NSZone *)zone
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instace = [super allocWithZone:zone];
});
return _instace;
}
+ (instancetype)sharedDataTool
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instace = [[self alloc] init];
});
return _instace;
}
- (id)copyWithZone:(NSZone *)zone
{
return _instace;
}
//重写函数
- (oneway void)release { }
- (id)retain { return self; }
- (NSUInteger)retainCount { return 1;}
- (id)autorelease { return self;}