objective-c中的Singleton单例模式的完整实现示例

本文详细介绍了一种Objective-C中的单例模式实现方法,通过使用synchronized确保线程安全,并利用C++析构函数实现单例对象的正确释放。文章提供了完整的Singleton类实现代码,包括如何重写alloc等方法来保证单例的唯一性。

Objective中单例模式的实现,应该是比较完整的包括了objc的单例的各个点。详细看代码注释,注意最后用c++的析构函数实现instance的释放,所以源文件类型必须是.mm格式。

Singleton.h

//

//Singleton.h

//singleton

//

//Created by leondun on 11-4-20.

//Copyright 2011 leondun. All rights reserved.

//

#import<Foundation/Foundation.h>

@interfaceSingleton : NSObject {

}

+(Singleton*)getInstance;

@end

Singleton.mm

#import"Singleton.h"

staticSingleton* instance =nil;

@interfaceSingleton(privateMethods)

-(void)realRelease;

@end

@implementationSingleton

//获取单例

+(Singleton*)getInstance

{

@synchronized(self) {

if(instance ==nil) {

[[selfalloc]init];

}

}

returninstance;

}

//唯一一次alloc单例,之后均返回nil

+ (id)allocWithZone:(NSZone*)zone

{

@synchronized(self) {

if(instance ==nil) {

instance = [superallocWithZone:zone];

returninstance;

}

}

returnnil;

}

//copy返回单例本身

- (id)copyWithZone:(NSZone*)zone

{

returnself;

}

//retain返回单例本身

- (id)retain

{

returnself;

}

//引用计数总是为1

- (unsigned)retainCount

{

return1;

}

//release不做任何处理

- (void)release

{

}

//autorelease返回单例本身

- (id)autorelease

{

returnself;

}

//真release私有接口

-(void)realRelease

{

[superrelease];

}

//

-(void)dealloc

{

//⋯⋯

printf("举例:在此处做一些单例结束时的收尾处理/n");

[superdealloc];

}

@end

//程序结束时析构静态c++类对象garbo,

//在Garbo类的析构函数中释放instance

structGarbo

{

~Garbo(){[instance realRelease];}

};

staticGarbo garbo;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值