首页 > 其他 > 详细

单例模式

时间:2016-03-05 00:00:59      阅读:194      评论:0      收藏:0      [点我收藏+]

SigleTon.h文件

#import <Foundation/Foundation.h>

@interface SigleTon : NSObject<NSCopying>

+(SigleTon *)shareInstance;

@end

 

 

SigleTon.m文件

#import "SigleTon.h"

@implementation SigleTon

 

static SigleTon *sigleton;

 

+(SigleTon *)shareInstance

{

    if (sigleton==nil)

    {

        sigleton=[[SigleTon alloc] init];

    }

    return sigleton;

    

}

 

//重写allocWithZone的方法

+(instancetype)allocWithZone:(struct _NSZone *)zone

{

    if (sigleton==nil)

    {

        sigleton=[super allocWithZone:zone];

    }

    return sigleton;

}

 

//重写copyWithZone的方法

-(id)copyWithZone:(NSZone *)zone

{

    return self;

}

@end

 

 

main.m文件

        SigleTon *sing1=[SigleTon shareInstance];

        SigleTon *sing2=[SigleTon shareInstance];

        SigleTon *sing3=[[SigleTon alloc] init];;

        SigleTon *sing4=[SigleTon new];

        SigleTon *sing5=[sing4 copy];

       

        NSLog(@"%p",sing1);

        NSLog(@"%p",sing2);

        NSLog(@"%p",sing3);

        NSLog(@"%p",sing4);

        NSLog(@"%p",sing5);

运行结果如下

2016-03-04 22:27:41.643 单例模式[2166:239114]  0x100106bf0

2016-03-04 22:27:41.643 单例模式[2166:239114] 0x100106bf0

2016-03-04 22:27:41.643 单例模式[2166:239114] 0x100106bf0

2016-03-04 22:27:41.644 单例模式[2166:239114] 0x100106bf0

2016-03-04 22:27:41.644 单例模式[2166:239114] 0x100106bf0

由结果可以看出,每一个对象的地址都是一样的,保证了每一个实例的对象都是同一个

单例模式的要点:

一是某个类只能有一个实例;

二是它必须自行创建这个实例;

三是它必须自行向整个系统提供这个实例。

单例模式

原文:http://www.cnblogs.com/layios/p/5243696.html

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