您的位置:首页 > 其它

137,单例模式

2015-12-24 13:36 218 查看
Tools.h:

#import <Foundation/Foundation.h>

@interface Tools :NSObject <NSCopying,NSMutableCopying>

//类方法->单例格式:share+类名或default+类名

+(instancetype)shareTools;

@end

Tools.m:

#import "Tools.h"

@implementation Tools

+(instancetype)shareTools{

Tools *instance = [[selfalloc]init];

return instance;

}

static Tools *_instance =nil;

//每一次调用alloc方法都会调用一次allocWithZone

+(instancetype)allocWithZone:(struct_NSZone *)zone{

NSLog(@"%s",__func__);

/* if (_instance == nil) {

NSLog(@"创建对象");

_instance = [[super allocWithZone:zone]init];

}*/

//以下代码在多线程中也能保证只执行一次

static dispatch_once_t onceToken;

dispatch_once(&onceToken,^{

_instance = [[superallocWithZone:zone]
init];

});

return_instance;

}

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

NSLog(@"");

return_instance;

}

-(instancetype)mutableCopyWithZone:(NSZone *)zone{

return_instance;

}

@end

main.m:

#import <Foundation/Foundation.h>

#import "Tools.h"

/*

单例模式:类的对象成为系统中唯一的实例,提供一个访问点,供客户类,共享资源

*/

int main(int argc,const
char * argv[]) {

Tools *t1 = [Toolsnew];

Tools *t2 = [[Toolsalloc]init];

Tools *t3 = [ToolsshareTools];

Tools *t4 = [t3
copy];

Tools *t5 = [t3
mutableCopy];

NSLog(@"t1 = %p,t2 = %p,t3 = %p,t4 = %p,t5 = %p",t1,t2,t3,t4,t5);

return 0;

}

//2015-12-24 12:25:07.865 19,单例模式[1716:302342] +[Tools allocWithZone:]

//2015-12-24 12:25:07.866 19,单例模式[1716:302342]创建对象

//2015-12-24 12:25:07.866 19,单例模式[1716:302342] +[Tools allocWithZone:]

//2015-12-24 12:25:07.866 19,单例模式[1716:302342] +[Tools allocWithZone:]

//2015-12-24 12:25:07.866 19,单例模式[1716:302342] t1 = 0x100200740,t2 = 0x100200740,t3 = 0x100200740,t4 = 0x100200740,t5 = 0x100200740

//Program ended with exit code: 0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: