单例模式的意思就是这个类只有一个实例,这个类就是单例类。在iOS中有不少都是单例NSNull,NSFileManager ,UIApplication,NSUserDefaults ,UIDevice,还有一些第三方也有能用到了这种设计模式例如Afhttpmanger。。。
(1)单例模式的作用 :可以保证在程序运行过程,一个类只有一个实例,而且该实例易于供外界访问,从而方便地控制了实例个数,并节约系统资源。
(2)单例模式的使用场合:在整个应用程序中,共享一份资源(这份资源只需要创建初始化1次),应该让这个类创建出来的对象永远只有一个。
实现思路:
- 创建一个一个全局的static的实例 static id _instance;
- 提供1个类方法让外界访问唯一的实例
- 重写allocWithzone:方法,控制内存分配。因为alloc内部会调用该方法,每次调用allocWithzone:方法,系统都会创建一块新的内存空间。
- 实现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 在控制其中创建单例类的对象,打印地址: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 - (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,0