天天看点

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

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

Singleton.h

//

//  Singleton.h

//  singleton

//

//  Created by leondun on 11-4-20.

//  Copyright 2011 leondun. All rights reserved.

//

#import <Foundation/Foundation.h>

@interface Singleton : NSObject {

}

+(Singleton *)getInstance;

@end

Singleton.mm

#import "Singleton.h"

static Singleton * instance = nil;

@interface Singleton(privateMethods)

-(void)realRelease;

@end

@implementation Singleton

//获取单例

+(Singleton *)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

- (unsigned)retainCount

{

    return 1;

}

//release不做任何处理

- (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;