单例模式

创建单例的基本步骤:
1、声明一个单件对象的静态实例,并初始化为nil
2、创建一个类的类工厂方法,生成一个该类的实例,当且仅当这个类的实例为nil时
3、覆盖allocWithZone:方法,确保用户(程序员)在直接分配和初始化对象时,不会产生另一个对象。
4、实现NScopying协议,覆盖release,autorelease,retain,retainCount方法,以此确保单例的状态。
5、在多线程的环境中,注意实用@synchronized关键字,确保静态实例被正确的创建和初始化。
#import <Foundation/Foundation.h> @interface Single : NSObject<NSCopying> @property (nonatomic,copy) NSString *username; @property (nonatomic,copy) NSString *email; + (id)shareSingle; @end
#import "Single.h" //第一步 static Single *single = nil; @implementation Single //第二步 + (id)shareSingle { //第五步,加同步锁 @synchronized(self) { if (single == nil) { single = [[[self class] alloc] init]; } } return single; } //第三步 + (id)allocWithZone:(NSZone *)zone { if (single == nil) { single = [super allocWithZone:zone]; } return single; } //第四步 - (id)copyWithZone:(NSZone *)zone { return single; } - (id)retain { return single; } - (NSUInteger)retainCount { return 1; } - (oneway void)release { } - (id)autorelease { return single; } @end
#import <Foundation/Foundation.h> #import "Single.h" int main(int argc, const char * argv[]) { @autoreleasepool { Single *single = [Single shareSingle]; Single *single2 = [Single shareSingle]; Single *single3 = [[Single alloc] init]; Single *single4 = [single copy]; [single release]; [single release]; [single release]; [single release]; [single release]; } return 0; }

所有地址都是同一个
浙公网安备 33010602011771号