iOS设计模式之单例

  单例模式的意思就是这个类只有一个实例,这个类就是单例类。在iOS中有不少都是单例NSNull,NSFileManager ,UIApplication,NSUserDefaults ,UIDevice,还有一些第三方也有能用到了这种设计模式例如Afhttpmanger。。。

(1)单例模式的作用 :可以保证在程序运行过程,一个类只有一个实例,而且该实例易于供外界访问,从而方便地控制了实例个数,并节约系统资源。

(2)单例模式的使用场合:在整个应用程序中,共享一份资源(这份资源只需要创建初始化1次),应该让这个类创建出来的对象永远只有一个。 

实现思路:

  1.   创建一个一个全局的static的实例   static id _instance;
  2.   提供1个类方法让外界访问唯一的实例
  3.   重写allocWithzone:方法,控制内存分配。因为alloc内部会调用该方法,每次调用allocWithzone:方法,系统都会创建一块新的内存空间。
  4.   实现copyWithZone:方法
//
//  AudioPlayer.m
//  单例
//
//  Created by 两好三坏 on 16/2/21.
//  Copyright © 2016年 ;. All rights reserved.
//

#import "AudioPlayer.h"

@interface AudioPlayer ()<NSCopying>

@end

@implementation AudioPlayer

//创建一个一个全局的static的实例   static id _instance;

static id _instance;

//提供1个类方法让外界访问唯一的实例

+(instancetype)shareAudioPlayer{
    
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
    
        _instance = [[self alloc] init];

    });
    
    return _instance;
}

//重写allocWithzone:方法,控制内存分配。因为alloc内部会调用该方法,每次调用allocWithzone:方法,系统都会创建一块新的内存空间。

+(instancetype)allocWithZone:(struct _NSZone *)zone{

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone];
    });
    return _instance;
}

//实现copyWithZone:方法

-(id)copyWithZone:(NSZone *)zone{
    return _instance;
}



@end

在控制其中创建单例类的对象,打印地址:

- (void)viewDidLoad {
    [super viewDidLoad];

        AudioPlayer *player1 = [AudioPlayer shareAudioPlayer];

        AudioPlayer *player2 = [[AudioPlayer alloc] init];
    
        AudioPlayer *player3 = [AudioPlayer new];
    
        AudioPlayer *player4 = [player1 copy];
    
    NSLog(@"%p,%p,%p,%p",player1,player2,player3,player4);
    
}


//打印结果
2016-02-21 23:27:13.990 单例[2847:329685] 0x7fb6e3e080a0,0x7fb6e3e080a0,0x7fb6e3e080a0,0x7fb6e3e080a0

  四个实例的内存地址是一样的,证明只创建了一个实例;

MRC环境下通常需要在实现下面几个方法:

- (oneway void)release {}
- (id)retain { return _instance; }
- (id)autorelease { return _instance; }
- (NSUInteger)retainCount { return UINT_MAX; }

  可以使用宏判断是否为mrc,

#if __has_feature(objc_arc)
 // ARC 
#else
 // MRC 
#endif

  

当然还可以把单例也抽取成为宏,用起来还挺方便的;你们也可以试试试~~~ 

原文地址:https://www.cnblogs.com/suqiankun/p/5205787.html