关闭

单例模板一则

395人阅读 评论(0) 收藏 举报

参考我上一篇转载的博文,我对单例模板做出了一些修改,用起来的话会变得更加方便一点:

//

//  SynthesizeSingleton.h

//  CocoaWithLove

//

//  Created by Matt Gallagher on 20/10/08.

//  Copyright 2009 Matt Gallagher. All rights reserved.

//

//  Permission is given to use this source code file without charge in any

//  project, commercial or otherwise, entirely at your risk, with the condition

//  that any redistribution (in part or whole) of source code must retain

//  this copyright and permission notice. Attribution in compiled projects is

//  appreciated but not required.

//


#define SYNTHESIZE_SINGLETON_FOR_CLASS(classname) \

\

static classname *instance = nil; \

\

+ (classname *)getInstance \

{ \

@synchronized(self) \

{ \

if (instance == nil) \

{ \

instance = [[self alloc] init]; \

} \

} \

\

return instance; \

} \

\

+ (id)allocWithZone:(NSZone *)zone \

{ \

@synchronized(self) \

{ \

if (instance == nil) \

{ \

instance = [super allocWithZone:zone]; \

return instance; \

} \

} \

\

return nil; \

} \

\

- (id)copyWithZone:(NSZone *)zone \

{ \

return self; \

} \

\

- (id)retain \

{ \

return self; \

} \

\

- (NSUInteger)retainCount \

{ \

return NSUIntegerMax; \

} \

\

- (void)release \

{ \

} \

\

- (id)autorelease \

{ \

return self; \

}

有了上面的宏模板,就再也不用机械化的多次复制粘贴以下代码了:

/**

 * 单例~

 */

+(AudioManager *) getInstance {

static AudioManager *instance;

@synchronized(self) {

if (!instance) {

instance = [[self allocinit];

}

}

return instance;

}

其实本质来说,还是粘贴复制,不过现在只要复制粘贴一句了

SYNTHESIZE_SINGLETON_FOR_CLASS(AudioManager)

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:2090603次
    • 积分:22757
    • 等级:
    • 排名:第304名
    • 原创:232篇
    • 转载:740篇
    • 译文:1篇
    • 评论:188条
    最新评论