單例模式
保證程序的整個生命周期中,只會創建一個單例類的實例。應用,適用場景
輕松實現兩個不同類之間的數據通信。
創建
//
// User.h
// LearnSingleton
//
// Created by 印林泉 on 2017/3/1.
// Copyright ? 2017年 yiq. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface User : NSObject
@property (nonatomic, copy) NSString *username;
@property (nonatomic, assign) NSInteger age;
+ (instancetype)shareUser;
@end
//
// User.m
// LearnSingleton
//
// Created by 印林泉 on 2017/3/1.
// Copyright ? 2017年 yiq. All rights reserved.
//
#import "User.h"
@implementation User
static User *user = nil;
+ (instancetype)shareUser {
// //互斥鎖,消耗資源
// @synchronized (self) {
// if (!user) {
// user = [[self alloc]init];
// }
// }
//GCD創建單例
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if (!user) {
user = [[self alloc]init];
}
});
return user;
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if (!user) {
user = [[self alloc]init];
}
});
return user;
}
- (id)copy {
return user;
}
- (id)mutableCopy {
return user;
}
- (NSString *)description {
return [NSString stringWithFormat:@"username: %@, age: %zd", _username, _age];
}
@end
存儲
//
// LoginView.m
// LearnSingleton
//
// Created by 印林泉 on 2017/3/1.
// Copyright ? 2017年 yiq. All rights reserved.
//
#import "LoginView.h"
#import "User.h"
@implementation LoginView
- (void)login {
User *user = [User shareUser];
user.username = @"yinlinqvan";
user.age = 25;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
}
*/
@end
讀取
//
// SettingView.m
// LearnSingleton
//
// Created by 印林泉 on 2017/3/1.
// Copyright ? 2017年 yiq. All rights reserved.
//
#import "SettingView.h"
#import "User.h"
@implementation SettingView
- (void)about {
User *user = [User shareUser];
NSLog(@"%@", user);
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
}
*/
@end
應用
//
// ViewController.m
// LearnSingleton
//
// Created by 印林泉 on 2017/3/1.
// Copyright ? 2017年 yiq. All rights reserved.
//
#import "ViewController.h"
#import "User.h"
#import "LoginView.h"
#import "SettingView.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
LoginView *loginView = [[LoginView alloc] init];
[loginView login];
SettingView *settingView = [[SettingView alloc]init];
[settingView about];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
程序不被殺死,該對象不變釋放。通過這樣的單例使用,讓所有類共享使用這個單例。用戶數據共享,輕松實現兩個不同類之間的數據通信。
可以保證單例類只有一個實例存在,整個系統只需要一個全局對象,有利于協調系統行為。
用戶信息存儲,在登錄時將整個用戶信息獲取,存放在本地文件,這些配置數據,由單例對象統一讀取,將服務進程中的其他對象通過單例獲取配置信息。簡化在復雜環境下的配置管理。