第一种,通过@synchronized实现。
AccessTokenTool1.h
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface AccessTokenTool1 : NSObject
@property (nonatomic, assign) NSInteger tokenType;
// 单例模式1
+ (AccessTokenTool1 *)getShareInstance;
// 获取Token
- (NSString *)getAccessToken;
@end
NS_ASSUME_NONNULL_END
AccessTokenTool1.m
#import "AccessTokenTool1.h"
static AccessTokenTool1 *singletonTool = nil;
@interface AccessTokenTool1()
@end
@implementation AccessTokenTool1
#pragma mark - SingletonPattern
// 单例模式1
+ (AccessTokenTool1 *)getShareInstance {
@synchronized (self) {
if (singletonTool == nil) {
singletonTool = [[self alloc] init];
}
return singletonTool;
}
}
// 获取Token
- (NSString *)getAccessToken {
if (self.tokenType == 0) {
return @"e10adc3949ba59abbe56e057f20f883e";
}
else {
return @"c33367701511b4f6020ec61ded352059";
}
}
@end
调用者ViewController.m
#import "ViewController.h"
#import "AccessTokenTool1.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
// 获取单例1
AccessTokenTool1 *tool = [AccessTokenTool1 getShareInstance];
tool.tokenType = 0;
NSLog(@"token = %@", [tool getAccessToken]);
}
@end
控制台输出日志信息:
2020-02-29 19:46:44.280786+0800 SingletonPatternDemo[26358:511145] token = e10adc3949ba59abbe56e057f20f883e
第二种,通过dispatch_once_t实现。
AccessTokenTool2.h
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface AccessTokenTool2 : NSObject
@property (nonatomic, assign) NSInteger tokenType;
// 单例模式2
+ (AccessTokenTool2 *)getShareInstance;
// 获取Token
- (NSString *)getAccessToken;
@end
NS_ASSUME_NONNULL_END
AccessTokenTool2.m
#import "AccessTokenTool2.h"
@interface AccessTokenTool2()
@end
@implementation AccessTokenTool2
#pragma mark - SingletonPattern
// 单例模式2
+ (AccessTokenTool2 *)getShareInstance {
static AccessTokenTool2 *singletonTool = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
singletonTool = [[self alloc] init];
});
return singletonTool;
}
// 获取Token
- (NSString *)getAccessToken
{
if (self.tokenType == 0) {
return @"e10adc3949ba59abbe56e057f20f883e";
}
else {
return @"c33367701511b4f6020ec61ded352059";
}
}
@end
调用者ViewController.m
#import "ViewController.h"
#import "AccessTokenTool2.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
// 获取单例2
AccessTokenTool2 *tool = [AccessTokenTool2 getShareInstance];
tool.tokenType = 1;
NSLog(@"token = %@", [tool getAccessToken]);
}
@end
控制台输出日志信息:
2020-02-29 19:49:30.576020+0800 SingletonPatternDemo[26412:512987] token = c33367701511b4f6020ec61ded352059