@qixingguaizhuang
2016-05-24T12:15:30.000000Z
字数 1246
阅读 633
单例模式是一种常用的软件设计模式。
在它的核心结构中只包含一个被称为单例类的特殊类。通过单例模式可以保证系统中一个类只有一个实例而且该实例易于外界访问,从而方便对实例个数的控制并节约系统资源。如果希望在系统中某个类的对象只能存在一个,单例模式是最好的解决方案。
简单的说,单例是一个特殊的实例,在单例所属的类中只存在单例这么一个实例,并且单例类似全局变量,在系统任意地方都能访问单例.
单例对象的特点
单例对象应用的场景
创建视频播放器 GCD 单例为例:
@implementation SDP_ViewForAVPlayerWithUrl
因为实例是全局的,因此要定义为全局变量,且需要存储在静态区,不释放。不能存储在栈区。静态区,防止外界访问.
static SDP_ViewForAVPlayerWithUrl *ViewPlayer = nil;
// .h 中声明出单例接口
// 这里的 alloc 会调用下面的 alloc 方法
+ (instancetype)shareVideoPlayer{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
ViewPlayer = [[self alloc]initWithFrame:CGRectMake(0, 0, HEIGHT, WIDTH)];
});
return ViewPlayer;
}
// 这个方法服务于 alloc ,不论外界调用多少次 alloc ,分配的空间地址都是一个
+ (instancetype)allocWithZone:(struct _NSZone *)zone{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
ViewPlayer = [super allocWithZone:zone];
});
return ViewPlayer;
}
//避免外界实现 copy 方法,所以当调用 copy 方法时,直接返回其本身。因为我们希望 ViewPlayer 作为单例,所以 V1 调用 copy 时应该,直接返回本身。记得签订<NSCopying>协议。
SDP_ViewForAVPlayerWithUrl * V1 = [SDP_ViewForAVPlayerWithUrl shareVideoPlayer]
SDP_ViewForAVPlayerWithUrl * V2 = [V1 copy];
方法如下:
- (id)copyWithZone:(NSZone *)zone{
return ViewPlayer;
}
dispatch_once
dispatch_once 可以用来初始化一些全局的数据,它能够确保block代码在app的生命周期内仅被运行一次,而且还是线程安全的,不需要额外加锁。