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

被折叠的 条评论
为什么被折叠?



