博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
单例模式
阅读量:4703 次
发布时间:2019-06-10

本文共 1262 字,大约阅读时间需要 4 分钟。

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

你可能感兴趣的文章
jquery之遍历与事件
查看>>
js对象
查看>>
网页状态码
查看>>
Native开发与JNI机制详解
查看>>
TreeSet基本用法
查看>>
Linux cmus
查看>>
MySQL面试题
查看>>
Storm-0.9.3新特性
查看>>
基于visual Studio2013解决面试题之0503取最大数字字符串
查看>>
RTX基础教程目录
查看>>
instr
查看>>
centos6.9 安装mysql8
查看>>
AX2009使用NPOI导出EXCEL
查看>>
CocoaChina六年了,记我的这六年——六年汇总
查看>>
angular4 ionic3 app
查看>>
HDU 2036 改革春风吹满地 数学题
查看>>
[ActionScript 3.0] AS3 绘制正八面体(线条)
查看>>
.Module高内聚低耦合的思考
查看>>
最短路模板(SPFA POJ2387)
查看>>
windows用户态和内核态
查看>>