单例模式:(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