您的位置:首页 > 移动开发 > Objective-C

Singleton Pattern in Objective-C

2010-10-27 19:58 337 查看
Creating a Singleton Instance

A singleton object acts as a kind of control center, directing or coordinating the services of the class. Your class should generate a singleton instance rather than multiple instances when there is conceptually only one instance (as with, for example, NSWorkspace). You use singleton instances rather than factory methods or functions when it is conceivable that there might be multiple instances one day.

To create a singleton as the sole allowable instance of a class in the current process, you need to have an implementation similar to the code below. This code does the following:

■Declare a static instance of your singleton object and initialize it to nil.

■In your class factory method for the class (named something like “sharedInstance” or “getInstance”),

generate an instance of the class but only if the static instance is nil.

■Override the allocWithZone: method to ensure that another instance is not allocated if someone tries to allocate and initialize an instance of your class directly instead of using the class factory method. Instead, just return the shared object.

■Implement the base protocol methods copyWithZone:, release, retain, retainCount, and autorelease to do the appropriate things to ensure singleton status. (The last four of these methods apply to memory-managed code, not to garbage-collected code.)

Creating a Singleton Instance

//
//MySingletonClass.m
//Created by Tracy E on 10-10-27.
//Copyright 2010 tracy.cpp@gmail.com All rights reserved.
//

#import "MySingletonClass.h"

static MySingletonClass *singletonInstance = nil;

@implementation MySingletonClass

+ (id)getInstance {
if (singletonInstance == nil)
{
singletonInstance = [[super allocWithZone:NULL] init];
}
returnsingletonInstance;
}

+ (id)allocWithZone:(NSZone *)zone
{
return [[self getInstance] retain];
}

- (id)copyWithZone:(NSZone *)zone {
returnself;
}
- (id)retain {
returnself;
}

- (NSUInteger)retainCount {
returnNSUIntegerMax; //denotes an object that cannot be released
}

- (void)release {
//do nothing
}

- (id)autorelease {
returnself;
}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: