设计模式——单例

单例,确保程序运行中该类只有一个实例,常用于资源共享。例如:[UIApplication sharedApplication];

OC写法:

#import 

@interface Review_SingleInstance : NSObject
+(Review_SingleInstance *)shareInstance;
@end

#import "Review_SingleInstance.h"

@implementation Review_SingleInstance

static Review_SingleInstance *_instance = nil;

+(Review_SingleInstance *)shareInstance{   

    static dispatch_once_t onceToken;   

    dispatch_once(&onceToken, ^{       

        _instance = [[[self class] alloc] init];   

    });   

    return _instance;

}
//为了防止使用alloc、new重复创建对象,需要添加下面方法
+(instancetype)allocWithZone:(struct _NSZone *)zone{   

    static dispatch_once_t onceToken;   

    dispatch_once(&onceToken, ^{       

        _instance = [super allocWithZone:zone];   

    });   

    return _instance;

}

调用:

Review_SingleInstance *instance1 = [Review_SingleInstance shareInstance];    
NSLog(@"%@",instance1);

Swift写法:

import UIKit

class RISDesignPattern:NSObject{

    // MARK: - 单例

    static let instance : RISDesignPattern = RISDesignPattern()

    private override init() {

    }

}

调用:

// MARK: - 实例化设计模式 - 单例   

let designPattern = RISDesignPattern.instance

关于单例类属性的问题

单例类中属性赋值 - 需要创建获取空间的属性,要放在shareInstance中,才不会重复创建,因为init方法会被重新执行

你可能感兴趣的:(设计模式——单例)