首页 > 其他 > 详细

单例设计模式

时间:2015-12-08 21:44:00      阅读:143      评论:0      收藏: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

 

 

单例设计模式

原文:http://www.cnblogs.com/WJR12/p/5030871.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!