单例模式

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

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

单例模式的要点:

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

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

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

原文地址:https://www.cnblogs.com/layios/p/5243696.html