单例模板一则

本文介绍了一个用于实现单例模式的宏模板,通过简单的宏定义即可为任意类快速创建线程安全的单例实例,避免了传统复制粘贴单例代码的繁琐。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

//

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

staticAudioManager*instance;

@synchronized(self) {

if(!instance) {

instance = [[selfalloc]init];

}

}

returninstance;

}

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

SYNTHESIZE_SINGLETON_FOR_CLASS(AudioManager)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值