[IOS 下重温设计模式] - Singleton

View Code
@interface Singleton : NSObject 
{

}

+ (Singleton *) sharedInstance;

- (void) operation;


@end
View Code
#import "Singleton.h"


@implementation Singleton


static Singleton *sharedSingleton_ = nil;

- (void) operation
{
// do something
NSLog(@"Singleton");
}

+ (Singleton *) sharedInstance
{
if (sharedSingleton_ == nil)
{
sharedSingleton_ = [NSAllocateObject([self class], 0, NULL) init];
}

return sharedSingleton_;
}


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


- (id) copyWithZone:(NSZone*)zone
{
return self;
}

- (id) retain
{
return self;
}

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

- (void) release
{
// do nothing
}

- (id) autorelease
{
return self;
}

@end

=============================

View Code
@interface MySingleton : Singleton
{

}

@end
View Code
@implementation MySingleton

- (id) init
{

return self;
}

- (void) operation
{
// do something
NSLog(@"MySingleton");
}

@end

=============================

client:

View Code
  Singleton *s = [MySingleton sharedInstance];

[s operation];






posted @ 2011-10-21 10:43  Gang.Wang  阅读(376)  评论(0编辑  收藏  举报