Objective-C的单例模式(singleton)
2012-03-28 12:47
369 查看
如果你准备写一个类,希望保证只有一个实例存在,同时可以得到这个特定实例提供服务的入口,那么可以使用单态设计模式。
单态模式在Java、C++中很常用,在Cocoa里,也可以实现。
但是,
Objective-C的单例模式绝对和你所想象不一样,他的写法和你所见过的所有语言的写法都不一样。
官方建议
由于自己设计单态模式存在一定风险,主要是考虑到可能在多线程情况下会出现的问题,因此苹果官方建议使用以下方式来实现单态模式:
static MyGizmoClass *sharedGizmoManager = nil;
+ (MyGizmoClass*)sharedManager
{
@synchronized(self) {
if (sharedGizmoManager == nil) {
[[self alloc] init]; // assignment not done here
}
}
return sharedGizmoManager;
}
+ (id)allocWithZone:(NSZone *)zone
{
@synchronized(self) {
if (sharedGizmoManager == nil) {
sharedGizmoManager = [super allocWithZone:zone];
return sharedGizmoManager; // assignment and return on first allocation
}
}
return nil; //on subsequent allocation attempts return nil
}
- (id)copyWithZone:(NSZone *)zone
{
return self;
}
- (id)retain
{
return self;
}
- (unsigned)retainCount
{
return UINT_MAX; //denotes an object that cannot be released
}
- (void)release
{
//do nothing
}
- (id)autorelease
{
return self;
}
单态模式在Java、C++中很常用,在Cocoa里,也可以实现。
但是,
Objective-C的单例模式绝对和你所想象不一样,他的写法和你所见过的所有语言的写法都不一样。
官方建议
由于自己设计单态模式存在一定风险,主要是考虑到可能在多线程情况下会出现的问题,因此苹果官方建议使用以下方式来实现单态模式:
static MyGizmoClass *sharedGizmoManager = nil;
+ (MyGizmoClass*)sharedManager
{
@synchronized(self) {
if (sharedGizmoManager == nil) {
[[self alloc] init]; // assignment not done here
}
}
return sharedGizmoManager;
}
+ (id)allocWithZone:(NSZone *)zone
{
@synchronized(self) {
if (sharedGizmoManager == nil) {
sharedGizmoManager = [super allocWithZone:zone];
return sharedGizmoManager; // assignment and return on first allocation
}
}
return nil; //on subsequent allocation attempts return nil
}
- (id)copyWithZone:(NSZone *)zone
{
return self;
}
- (id)retain
{
return self;
}
- (unsigned)retainCount
{
return UINT_MAX; //denotes an object that cannot be released
}
- (void)release
{
//do nothing
}
- (id)autorelease
{
return self;
}
相关文章推荐
- Objective-C的单例模式(singleton)(转)
- Objective-C的单例模式(singleton)(转)
- Objective-C 单例模式singleton(参考apple官方例子)
- Objective-c 单例设计模式(Singleton)
- Objective-C使用单例(Singleton)模式
- Objective-C设计模式——单例Singleton(对象创建)
- Swift、Objective-C 单例模式 (Singleton)
- objective-c中的Singleton单例模式的完整实现示例
- Objective-C的单例模式(singleton)
- Objective —C 的单例模式 Singleton实现
- Objective-C中的单例模式(singleton)
- Swift、Objective-C 单例模式 (Singleton)
- objective_c 单例模式Singleton
- Objective-c 单例设计模式(Singleton)
- objective-c中的Singleton单例模式的完整实现示例
- objective-c 单例模式Singleton的实现
- Objective-C设计模式——单例Singleton(对象创建)
- Objective-C的单例模式(singleton)
- objective-c中的Singleton单例模式的完整实现示例
- (转)Objective-C的单例模式(singleton)