单例——单独的实例,只实例化一次,数据全局共享。
Swift
open class CD_Singleton {
private init() {}//必须要 private
open static let shared = CD_Singleton()
}
OC
---------- .h
#import <Foundation/Foundation.h>
@interface CD_Single : NSObject
#pragma mark ----- 单例及打印测试该单例 -----
@property(nonatomic,strong) NSString *name;
+ (CD_Single*)shared;
+ (void)cd_print;
@end
---------- .m
#import "CD_Single.h"
static CD_Single* shared = nil;
@implementation CD_Single
#pragma mark ----- 单例 -----
+ (CD_Single*) shared
{
static dispatch_once_t once;
dispatch_once(&once, ^{
if (shared == nil) {
shared = [[self alloc] init];
}
});
return shared;
}
/**
覆盖该方法主要确保当用户通过[[Singleton alloc] init]创建对象时对象的唯一性,alloc方法会调用该方法,只不过zone参数默认为nil,因该类覆盖了allocWithZone方法,所以只能通过其父类分配内存,即[super allocWithZone:zone]
*/
+(id)allocWithZone:(struct _NSZone *)zone
{
static dispatch_once_t token;
dispatch_once(&token, ^{
if(shared == nil){
shared = [super allocWithZone:zone];
}
});
return shared;
}
//自定义初始化方法
- (instancetype)init
{
self = [super init];
if(self){
}
return self;
}
//覆盖该方法主要确保当用户通过copy方法产生对象时对象的唯一性
- (id)copy
{
return self;
}
//覆盖该方法主要确保当用户通过mutableCopy方法产生对象时对象的唯一性
- (id)mutableCopy
{
return self;
}
//自定义描述信息,用于log详细打印
- (NSString *)description
{
return [NSString stringWithFormat:@"memeory address:%p,property name:%@",self,self.name];
}
//测试
+ (void)cd_print {
CD_Single *defaultManagerSingleton =[CD_Single shared];
NSLog(@"defaultManagerSingleton:\n%@",defaultManagerSingleton);
CD_Single *allocSingleton = [[CD_Single alloc] init];
NSLog(@"allocSingleton:\n%@",allocSingleton);
CD_Single *copySingleton = [allocSingleton copy];
NSLog(@"copySingleton:\n%@",copySingleton);
CD_Single *mutebleCopySingleton = [allocSingleton mutableCopy];
NSLog(@"mutebleCopySingleton:\n%@",mutebleCopySingleton);
}
@end
网友评论