单例模板一则

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

//

//  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)

posted on 2012-03-21 12:14  yang3wei  阅读(108)  评论(0编辑  收藏  举报