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

ios object-c 实现Singleton(单例)模式

2012-08-22 14:36 375 查看
转自:http://blog.csdn.net/txwyygbm/article/details/7211020

Singleton模式经常来做应用程序级别的共享资源控制, 应该说这个模式的使用频率非常高, 现在来看看在Objective-C里面的实现方法.

要实现一个Singleton Class, 至少需要做以下四个步骤:

1. 为Singleton Object实现一个静态实例, 初始化, 然后设置成nil.

2. 实现一个实例构造方法(通常命名为 sharedInstance 或者 sharedManager)检查上面声名的静态实例是否为nil, 如果是则新建并返回一个本类实例.

3. 重写 allocWithZone: 方法来保证当其他人直接使用 alloc 和 init 试图获得一个新实例的时候不会产生一个新的实例.

4. 适当的实现 copyWithZone:, release, retain, retainCount 和 autorelease.

@interface MySingleton : NSObject {

 

        // ...

 

}

 

+ (MySingleton *)sharedInstance;

 

// Interface

- (NSString *)helloWorld;

 

@end

#import "MySingleton.h"

static MySingleton *sharedInstance = nil;

 

@implementation MySingleton

#pragma mark Singleton methods

 

+ (MySingleton *)sharedInstance {

    @synchronized(self) {

        if (sharedInstance == nil) {

                        sharedInstance = [[MySingleton alloc] init];

                }

    }

    return sharedInstance;

}

 

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

    @synchronized(self) {

        if (sharedInstance == nil) {

            sharedInstance = [super allocWithZone:zone];

            return sharedInstance;  // assignment and return on first allocation

        }

    }

    return nil; // on subsequent allocation attempts return nil

}

 

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

    return self;

}

 

- (id)retain {

    return self;

}

 

- (unsigned)retainCount {

    return UINT_MAX;  // denotes an object that cannot be released

}

 

- (void)release {

    //do nothing

}

 

- (id)autorelease {

    return self;

}

 

#pragma mark -

#pragma mark NSObject methods

- (id)init {

        if (self = [super init]) {

                // ...

        }

        return self;

}

 

- (void)dealloc {

        // ...

 

        [super dealloc];

}

 

#pragma mark -

#pragma mark Implementation

 

- (NSString *)helloWorld {

        return @"Hello World!";

}

@end

#import "MySingleton.h"

 

// ...

 

NSLog(@"Result for singleton method helloWorld: %@", [[MySingleton sharedInstance] helloWorld]);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息