iOS单例模式(Singleton)
2015-10-28 16:29
295 查看
单例模式的意思就是只有一个实例。单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。这个类称为单例类。
1.单例模式的要点:
显然单例模式的要点有三个;一是某个类只能有一个实例;二是它必须自行创建这个实例;三是它必须自行向整个系统提供这个实例。
2.单例模式的优点:
1.实例控制:Singleton 会阻止其他对象实例化其自己的 Singleton 对象的副本,从而确保所有对象都访问唯一实例。
2.灵活性:因为类控制了实例化过程,所以类可以更加灵活修改实例化过程
IOS中的单例模式
在objective-c中要实现一个单例类,至少需要做以下四个步骤:
1、为单例对象实现一个静态实例,并初始化,然后设置成nil,
2、实现一个实例构造方法检查上面声明的静态实例是否为nil,如果是则新建并返回一个本类的实例,
3、重写allocWithZone方法,用来保证其他人直接使用alloc和init试图获得一个新实力的时候不产生一个新实例,
4、适当实现allocWitheZone,copyWithZone,release和autorelease。
下面以SurveyRunTimeData为例子:
static SurveyRunTimeData *sharedObj = nil; //第一步:静态实例,并初始化。
@implementation SurveyRunTimeData
+ (SurveyRunTimeData*) sharedInstance //第二步:实例构造检查静态实例是否为nil
{
@synchronized (self)
{
if (sharedObj == nil)
{
[[self alloc] init];
}
}
return sharedObj;
}
+ (id) allocWithZone:(NSZone *)zone //第三步:重写allocWithZone方法
{
@synchronized (self) {
if (sharedObj == nil) {
sharedObj = [super allocWithZone:zone];
return sharedObj;
}
}
return nil;
}
- (id) copyWithZone:(NSZone *)zone //第四步
{
return self;
}
- (id) retain
{
return self;
}
- (unsigned) retainCount
{
return UINT_MAX;
}
- (oneway void) release
{
}
- (id) autorelease
{
return self;
}
- (id)init
{
@synchronized(self) {
[super init];//往往放一些要初始化的变量.
return self;
}
}
@end
1.单例模式的要点:
显然单例模式的要点有三个;一是某个类只能有一个实例;二是它必须自行创建这个实例;三是它必须自行向整个系统提供这个实例。
2.单例模式的优点:
1.实例控制:Singleton 会阻止其他对象实例化其自己的 Singleton 对象的副本,从而确保所有对象都访问唯一实例。
2.灵活性:因为类控制了实例化过程,所以类可以更加灵活修改实例化过程
IOS中的单例模式
在objective-c中要实现一个单例类,至少需要做以下四个步骤:
1、为单例对象实现一个静态实例,并初始化,然后设置成nil,
2、实现一个实例构造方法检查上面声明的静态实例是否为nil,如果是则新建并返回一个本类的实例,
3、重写allocWithZone方法,用来保证其他人直接使用alloc和init试图获得一个新实力的时候不产生一个新实例,
4、适当实现allocWitheZone,copyWithZone,release和autorelease。
下面以SurveyRunTimeData为例子:
static SurveyRunTimeData *sharedObj = nil; //第一步:静态实例,并初始化。
@implementation SurveyRunTimeData
+ (SurveyRunTimeData*) sharedInstance //第二步:实例构造检查静态实例是否为nil
{
@synchronized (self)
{
if (sharedObj == nil)
{
[[self alloc] init];
}
}
return sharedObj;
}
+ (id) allocWithZone:(NSZone *)zone //第三步:重写allocWithZone方法
{
@synchronized (self) {
if (sharedObj == nil) {
sharedObj = [super allocWithZone:zone];
return sharedObj;
}
}
return nil;
}
- (id) copyWithZone:(NSZone *)zone //第四步
{
return self;
}
- (id) retain
{
return self;
}
- (unsigned) retainCount
{
return UINT_MAX;
}
- (oneway void) release
{
}
- (id) autorelease
{
return self;
}
- (id)init
{
@synchronized(self) {
[super init];//往往放一些要初始化的变量.
return self;
}
}
@end
相关文章推荐
- IOS无法正常发起请求
- iOS 单例模式
- 实现FPGA Verilog HDL与NIOS II的通信数据交换——利用PIO实现通信
- iOS开发中静态库和动态库区别
- iOS数据持久化之属性列表和归档
- iOS开发日记39-上传ERROR-90535,90529,90049
- 录制音频(AVAudioRecorder)for iOS
- ios开发-- xcode6创建静态库framework
- iOS程序退出后的本地通知
- iOS BLE开发关键步骤
- <iOS>一个开发中值得注意的细节
- perform selector may cause a leak in ARC
- iOS无限滚动,实现ios原生日历
- iOS程序性能优化
- 实现FPGA Verilog HDL与NIOS II的通信数据交换——利用AVALON总线
- ios的第一篇博客
- 文章标ios 9.0SDK 没有.dylib
- iOS 3DTouch
- NSThread - 2
- iOS:Git分布式版本控制器系统