简介
- 单例模式 —— 就是要实现在一个应用程序中,对应的一个类只会有一个实例,无论创建多少次,都是同一个对象.比如在一个应用程序中,aController里面要创建一个player类的对象,而bController里面又要创建一个player类的对象,这是我们就可以利用单例来实现在应用程序中只创建了一个player类的对象,这就可以有效地避免重复创建,浪费内存。
创建方法 —— 一般都是把share+类名这个方法写在.h文件来被调用,单例模式的创建一般不用alloc和init来调用
- 重写allocWithZone方法。alloc底层是调用allocWithZone方法的,所以我们只需重写allocWithZone方法。
#import "NTMoviePlayer.h"
@implementation NTMoviePlayer
static id moviePlayer;
+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
// 在这里判断,为了优化资源,防止多次加锁和判断锁
if (moviePlayer == nil) {
// 在这里加一把锁(利用本类为锁)进行多线程问题的解决
@synchronized(self){
if (moviePlayer == nil) {
// 调用super的allocWithZone方法来分配内存空间
moviePlayer = [super allocWithZone:zone];
}
}
}
return moviePlayer;
}
+ (instancetype)sharedMoviePlayer
{
if (moviePlayer == nil) {
@synchronized(self){
if (moviePlayer == nil) {
// 在这里写self和写本类名是一样的
moviePlayer = [[self alloc]init];
}
}
}
return moviePlayer;
}
- (id)copyWithZone:(NSZone *)zone
{
return moviePlayer;
}
@end
- load方法:当类加载到运行环境中的时候就会调用且仅调用一次,同时注意一个类只会加载一次(类加载有别于引用类,可以这么说,所有类都会在程序启动的时候加载一次,不管有没有在目前显示的视图类中引用到
#import "NTMusicPlayer.h"
@implementation NTMusicPlayer
static id musicPlayer;
+ (void)load
{
musicPlayer = [[self alloc]init];
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
if (musicPlayer == nil) {
musicPlayer = [super allocWithZone:zone];
}
return musicPlayer;
}
+ (instancetype)sharedMusicPlayer
{
return musicPlayer;
}
- (id)copyWithZone:(NSZone *)zone
{
return musicPlayer;
}
@end
#import "NTPicturePlayer.h"
@implementation NTPicturePlayer
static id picturePlayer;
+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
picturePlayer = [[super alloc]init];
});
return picturePlayer;
}
+ (instancetype)sharedPicturePlayer
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
picturePlayer = [[self alloc]init];
});
return picturePlayer;
}
- (id)copyWithZone:(NSZone *)zone
{
return picturePlayer;
}
@end
网友评论