/**
* (5) 写一个Person类,要保证无论什么情况下创建Person对象返回的都是同一个对象(单例设计模式)。(Objective-C)
*/
#import <Foundation/Foundation.h>
@interface Person : NSObject
+ (Person *)sharedManager;
@property (nonatomic,retain) NSString *name;
@property (nonatomic,assign) int age;
@end
#import "Person.h"
@implementation Person
//这句不能掉
static Person *person =nil;
+ (Person *)sharedManager
{
//单例需要使用dispatch_once_t线程
//这和dispatch_once配合使用能保该第二个参数代码块中的代码只被执行一次
//如果被执行过不执行直接返回静态变量person,未执行过静态变量person=nil自然需要开辟空间并初始化
static dispatch_once_t once;
dispatch_once(&once, ^{
person = [[self alloc] init];
});
return person;
}
@end
#import <Foundation/Foundation.h>
#import "Person.h"
int main(int argc, const char * argv[]) {
Person *person1 = [Person sharedManager];
Person *person2 = [Person sharedManager];
NSLog(@"%p", person1);
NSLog(@"%p", person2);
return 0;
}
|
|