Object -c 单例模式

单例模式:(Singleton)

类的对象只实例化一次,外界方便访问,提供共享数据,节约资源占用。


要点:

1.一个类只能实例化一次。

2.必须自行实例化。

3.必须向整个系统提供这个实例。


使用方式举例:


</pre><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; border: 0px; list-style: none; word-wrap: normal; word-break: normal; line-height: normal; font-size: 14px; text-indent: 28px; -webkit-text-stroke-width: initial; font-family: simsun; color: rgb(70, 70, 70); -webkit-text-stroke-color: rgb(70, 70, 70);"></p><pre name="code" class="objc">//
//  main.m
//  单例模式
//
//  Created by lzq on 16/4/5.
//  Copyright © 2016年 woyijiuai. All rights reserved.
//

#import
#import "Singleton.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // 打印对象地址
        Singleton *sin1=[Singleton shareSingleton];
        NSLog(@"%@",sin1);
        Singleton *sin2=[Singleton shareSingleton];
        NSLog(@"%@",sin2);
        Singleton *sin3=[Singleton shareSingleton];
        NSLog(@"%@",sin3);
        Singleton *sin4=[Singleton shareSingleton];
        NSLog(@"%@",sin4);
        Singleton *sin5=[Singl<pre name="code" class="objc">//
//  Singleton.m
//  单例模式
//
//  Created by lzq on 16/4/5.
//  Copyright © 2016年 woyijiuai. All rights reserved.
//

#import "Singleton.h"

@implementation Singleton

static Singleton* mySingle=nil;//创建一个静态的类方法

+(Singleton*)shareSingleton{
    
    if (mySingle==nil) {
        mySingle=[[Singleton alloc]init];
    }
    return mySingle;
}
@end

//
//  main.m
//  单例模式
//
//  Created by lzq on 16/4/5.
//  Copyright © 2016年 woyijiuai. All rights reserved.
//

#import
#import "Singleton.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // 打印对象地址
        Singleton *sin1=[Singleton shareSingleton];
        NSLog(@"%@",sin1);
        Singleton *sin2=[Singleton shareSingleton];
        NSLog(@"%@",sin2);
        Singleton *sin3=[Singleton shareSingleton];
        NSLog(@"%@",sin3);
        Singleton *sin4=[Singleton shareSingleton];
        NSLog(@"%@",sin4);
        Singleton *sin5=[Singleton shareSingleton];
        NSLog(@"%@",sin5);
    }
    return 0;
}

eton shareSingleton]; NSLog(@"%@",sin5); } return 0;}
 


输出:


2016-04-05 20:16:42.195 单例模式[2824:153436]

2016-04-05 20:16:42.196 单例模式[2824:153436]

2016-04-05 20:16:42.196 单例模式[2824:153436]

2016-04-05 20:16:42.196 单例模式[2824:153436]

2016-04-05 20:16:42.196 单例模式[2824:153436]

Program ended with exit code: 0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值