单例模式

Posted 翌日晨曦

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了单例模式相关的知识,希望对你有一定的参考价值。

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

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

单例模式的要点:

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

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

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

以上是关于单例模式的主要内容,如果未能解决你的问题,请参考以下文章

单例模式(单例设计模式)详解

Java模式设计之单例模式(二)

单例模式(饿汉式单例模式与懒汉式单例模式)

单例模式

单例模式

设计模式之单例模式