(一)單例模式:確保某一個類只有一個實例,而且自行實例化並向整個系統提供這個實例。
(二)單例模式的要點:
1、某個類只能有一個實例;
2、必須自行創建這個實例;
3、必須自行向整個系統提供這個實例。
(三)單例模式的優點:
//
// AYinstance.h
// 單例模式demo
//
// Created by 艾陽 on 15/10/28.
// Copyright © 2015年 艾陽. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface AYinstance : NSObject
+ (instancetype)sharedDataTool;
@end
//
// AYinstance.m
// 單例模式demo
//
// Created by 艾陽 on 15/10/28.
// Copyright © 2015年 艾陽. All rights reserved.
//
#import "AYinstance.h"
#import "AFNetworking.h"
@implementation AYinstance
// 用來保存唯一的單例對象
static id _instace;
+ (id)allocWithZone:(struct _NSZone *)zone
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instace = [super allocWithZone:zone];
});
return _instace;
}
+ (instancetype)sharedDataTool
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instace = [[self alloc] init];
});
return _instace;
}
- (id)copyWithZone:(NSZone *)zone
{
return _instace;
}
@end
總結:加上以上代碼的類就變成了單例模式的類,這個類只有一個實例,裏邊的變量、函數在整個項目都只有一套,整個程序都能訪問這個類並進行賦值和調用。