代码改变世界

单例设计模式

2015-12-08 20:27  AB小博客  阅读(150)  评论(0)    收藏  举报

main.m文件

#import <Foundation/Foundation.h>

#import "Person.h"

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

    @autoreleasepool {

        Person *per1 = [Person getInstance];

         NSLog(@"1");

        Person *per2 = [Person getInstance];

        Person *per3 = [per2 copy];

        

        NSLog(@"per1=%p",per1);

        NSLog(@"per2=%p",per2);

        NSLog(@"per3=%p",per3);

        

    }

    return 0;

}

 

Person.h文件

#import <Foundation/Foundation.h>

@interface Person : NSObject

{    

}

+(Person*)getInstance;

 

@end

Person.m文件

#import "Person.h"

static Person *instance = nil;

@interface Person();

-(instancetype)init;

@end

 

@implementation Person

-(instancetype)init{

    return self;

}

+(Person*)getInstance{

    if (instance==nil) {

        instance=[[Person alloc]init];

        NSLog(@"a");

    }

    

    return instance;

}

+(id)allocWithZone:(struct _NSZone *)zone{

    @synchronized(self) {

        if (!instance) {

            instance = [super allocWithZone:zone];

            NSLog(@"b");

            return instance;

        }

    }

    return nil;

}

-(id)copyWithZone:(NSZone *)zone;{

    NSLog(@"c");

    return self;

}

 

@end

输出结果

b

a

1

c

per1=0x1003000d0

 per2=0x1003000d0

 per3=0x1003000d0