iOS - 单例模式

SingletonPattern

取经的地址这里

1.单例模式作用和缺点####

  • 共享资源
  • 管理中心
  • 缺点:增加耦合

2.严格单例的要求####

  • 严格的单例模式是无法通过alloc init 方法来生成单例对象的。
  • 不能派生子类,即使派生子类,子类也无法创建单例对象。
  • 防止单例对象被释放。

3.单例模式的应用要求####

  • 单例模式接口要隐藏实现细节。
  • 使用单例模式需要对其进行上层的封装。

4.严格代码实现####

下载代码


#import "Singleton.h"

/*
   值得说明的是static关键词的作用,static修饰的变量是在程序运行开始就保存在内存的静态区中,静态区中还有的就是全局变量。这也是单例为什么能够实现共享数据的关键。
*/
static Singleton * _shareSingleton = nil;

@implementation Singleton

//*> 不允许使用init创建单例对象
- (instancetype)init
{
    [NSException raise:@"SingletonPattern"
                format:@"Cannot instance singleton using 'init' method, shareInstance must be used."];
    
    return nil;
}

//*> 不允许使用copy创建单例对象
- (id)copyWithZone:(NSZone *)zone
{
    [NSException raise:@"SingletonPattern"
                format:@"Cannot instance singleton using copy method, shareInstance must be used."];
    
    return nil;
}

+ (Singleton *)shareInstance
{
    if (self != [Singleton class])
    {
        [NSException raise:@"SingletonPattern"
                    format:@"Cannot use shareInstance method from subclass."];
    }

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _shareSingleton = [[Singleton alloc] initInstance];
    });
    
    return _shareSingleton;
}

- (id)initInstance
{
    return [super init];
}

@end

5.单例应用代码示范###

首先一定要满足,单例在应用中的几点规范。

测试代码

posted @ 2016-04-06 11:11  lvable  阅读(203)  评论(0编辑  收藏  举报