ios - 单例模式

2020-09-23  本文已影响0人  Fat_Blog

简介

创建方法 —— 一般都是把share+类名这个方法写在.h文件来被调用,单例模式的创建一般不用alloc和init来调用

#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
#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
上一篇 下一篇

猜你喜欢

热点阅读