标签:
什么是单例模式:(singleton)
单例模式的意图是类的对象成为系统中唯一的实例,提供一个访问点,供客户类共分享资源
单例类,必须提供一个接入点(特殊的类方法)
// SingletonTools.h // 单例模式实现 // // Created by CloudWalk on 15/9/11. // Copyright (c) 2015年 CloudWalk. All rights reserved. // #import <Foundation/Foundation.h> @interface SingletonTools : NSObject @property(nonatomic,assign) int num; @property(nonatomic, copy)NSString *s; // 单例的类,提供一个接入点 + (instancetype)shareInstance; @end
// SingletonTools.m // 单例模式实现 // // Created by CloudWalk on 15/9/11. // Copyright (c) 2015年 CloudWalk. All rights reserved. // #import "SingletonTools.h" SingletonTools *instance = nil; @implementation SingletonTools // 单利的接入点方法 + (instancetype)shareInstance { if(instance == nil) { instance = [[SingletonTools alloc] init]; return instance; } return instance; } @end
// Person.h // 单例模式实现 // // Created by CloudWalk on 15/9/11. // Copyright (c) 2015年 CloudWalk. All rights reserved. // #import <Foundation/Foundation.h> @interface Person : NSObject - (void)run; @end
// // Person.m // 单例模式实现 // // Created by CloudWalk on 15/9/11. // Copyright (c) 2015年 CloudWalk. All rights reserved. // #import "Person.h" #import "SingletonTools.h" @implementation Person - (void)run { SingletonTools *st = [SingletonTools shareInstance]; st.num = 100; st.s = @"jajf"; NSLog(@"%d %@",st.num, st.s); } @end
// main.m // 单例模式实现 // // Created by CloudWalk on 15/9/11. // Copyright (c) 2015年 CloudWalk. All rights reserved. // #import <Foundation/Foundation.h> #import "Person.h" #import "SingletonTools.h" int main(int argc, const char * argv[]) { @autoreleasepool { Person *p = [Person new]; [p run]; } return 0; }
复杂的单利 :copy,new,alloc 创建对象,都不会产生新的对象
// Person.m // Created by CloudWalk on 15/9/2. // Copyright (c) 2015年 CloudWalk. All rights reserved. // #import "Person.h" // 变量指向单例对象 static Person *singletonInstance = nil; @implementation Person + (id)sharePerson { // 线程锁 @synchronized(self) { // 创建一个单例实例 if (singletonInstance == nil) { singletonInstance = [[[self class] alloc] init]; } } return singletonInstance; } #pragma mark - 下面的方法为了确保只有一个实例对象 + (id)allocWithZone:(NSZone *)zone { if (singletonInstance == nil) { singletonInstance =[super allocWithZone:zone]; } return singletonInstance; } // 实现NSCopying协议 - (id)copyWithZone:(NSZone *)zone { return singletonInstance; } - (id)retain { return singletonInstance; } - (oneway void)release { } - (id)autorelease { return singletonInstance; } - (NSUInteger)retainCount { return UINT_MAX; } @end
标签:
原文地址:http://www.cnblogs.com/1023843587qq/p/4799746.html