objective-c中的Singleton单例模式的完整实现示例

转载自:http://blog.csdn.net/duboleon/article/details/6337174

Objective中单例模式的实现,应该是比较完整的包括了objc的单例的各个点。详细看代码注释,注意最后用c++的析构函数实现instance的释放,所以源文件类型必须是.mm格式。

//

//  FullSingleton.h

//  *********

//

//  Created by ********* on 12-2-23.

//  Copyright (c) 2012 ***********. All rights reserved.

//


#import <Foundation/Foundation.h>



@interface FullSingleton : NSObject {

    

}


+(FullSingleton *) getInstance;


@end




//

//  FullSingleton.mm

//  *********

//

//  Created by ********** on 12-2-23.

//  Copyright (c) 2012 *********. All rights reserved.

//


#import "FullSingleton.h"


static FullSingleton * instance = nil;


@interface FullSingleton(privateMethods)


-(void) realRelease;


@end



@implementation FullSingleton


// 获取单例~

+(FullSingleton*) getInstance {

    @synchronized(self) {

        if (instance == nil) {

            [[self alloc] init];

        }

    }

    return instance;

}


// 唯一一次 alloc 单例,之后均返回 nil~

+(id) allocWithZone:(NSZone *)zone {

    @synchronized(self) {

        if (instance == nil) {

            instance = [super allocWithZone:zone];

            return instance;

        }

    }

    return nil;

}


// copy 返回单例本身~

-(id) copyWithZone:(NSZone *)zone {

    return self;

}


// retain 返回单例本身~

-(id) retain {

    return self;

}


// 引用计数总是为 1~

-(NSUInteger) retainCount {

    return 1;

}


// release 不做任何处理~

-(oneway void) release {

    

}


// autorelease 返回单例本身~

-(id) autorelease {

    return self;

}


// release 私有接口~

-(void) realRelease {

    [super release];

}


//

-(void) dealloc {

    printf("举例:在此处做一些单例结束时的收尾处理/n"); 

    [super dealloc];

}


@end


// 程序结束时析构静态 c++ 类对象 garbo,在Garbo类的析构函数中释放instance~

struct Garbo {

    ~Garbo(){

        [instance realRelease];

    }

};

static Garbo garbo;




posted on 2012-02-23 15:18  yang3wei  阅读(278)  评论(0)    收藏  举报