objective-c 实现单例模式

使用objective-c 实现sington和其它语言稍有不同,网上有很多实现的版本.这里提供一个 textmate 包含的单例模板,供大家交流学习.

//

//Singleton.h

//

#import <Cocoa/Cocoa.h>

@interface Singleton:NSObject

{

}

+(Singleton*)sharedInstance;

@end

 

//

//Singleton.mm

// 

#import "Singleton.h"

static Singleton* SharedInstance;

@implementation Singleton

+(Singleton*)sharedInstance

{

   return SharedInstance?:[[self new] autorelease];

}

 

-(id)init

{

  if(SharedInstance)

  {

    [self release];

  }

  else if(self = SharedInstance = [[super init] retain])

  {

    /*init code */

  }

  return SharedInstance;

}

@end

 

注:摘自 Textmate 模板.

posted @ 2012-09-16 23:30  zanewin  阅读(134)  评论(0)    收藏  举报