什么是单例模式:(Singleton)
单例模式的意图是是的类的对象成为系统中唯一的实例,提供一个访问点,供客户类 共享资源。
什么情况下使用单例?
1、类只能有一个实例,而且必须从一个为人熟知的访问点对其进行访问,比如工厂方 法。
2、这个唯一的实例只能通过子类化进行扩展,而且扩展的对象不会破坏客户端代码。
单例设计模式的要点:
1) 某个类只能有一个实例。
2)他必须自行创建这个对象
3)必须自行向整个系统提供这个实例;
4)为了保证实例的唯一性,我们必须将
5)这个方法必须是一个静态类
下面看代码实现
Tools.h
#import <Foundation/Foundation.h>
@interface Tools : NSObject<NSCopying, NSMutableCopying>
// 一般情况下创建一个单利对象都有一个与之对应的类方法
// 一般情况下用于创建单利对象的方法名称都以share开头, 或者以default开头
+ (instancetype)shareInstance;
@end
Tools.m
#import "Tools.h"
static Tools *_instance = nil;//不能让外部访问,同时放在静态块中
@implementation Tools
+ (instancetype)shareInstance
{
if (_instance == nil) {
_instance = [[self alloc] init];
}
return _instance;
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
/*
// 当前代码在多线程中可能会出现问题
NSLog(@"%s", __func__);
// 由于所有的创建方法都会调用该方法, 所以只需要在该方法中控制当前对象只创建一次即可
if (_instance == nil) {
NSLog(@"创建了一个对象");
_instance = [[super allocWithZone:zone] init];
}
return _instance;
*/
// 以下代码在多线程中也能保证只执行一次
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [[super allocWithZone:zone] init];
});
return _instance;
}
// copyWithZone方法用什么调用? 对象
- (id)copyWithZone:(NSZone *)zone{
return _instance;
}
- (id)mutableCopyWithZone:(NSZone *)zone
{
return _instance;
}
- (oneway void)release
{
// 为保证整个程序过程中只有一份实例, \
在这个方法中什么都不做
}
- (instancetype)retain
{
return _instance;
}
- (NSUInteger)retainCount
{
// return 1;
// 注意: 为了方便程序员之前沟通, 一般情况下不会在单例中返回retainCount = 1
// 而是返回一个比较大得值
return MAXFLOAT;
}
@end