設計模式項目實戰(單例模式寫好一個登陸管理類)

單例模式(Singleton Pattern)是屬於屬於建立型模式,它提供了一種建立對象的最佳方式。 這種模式涉及到一個單一的類,該類負責建立本身的對象,同時確保只有單個對象被建立。這個類提供了一種訪問其惟一的對象的方式,能夠直接訪問,不須要實例化該類的對象。緩存

優勢:bash

一、在內存裏只有一個實例,減小了內存的開銷,尤爲是頻繁的建立和銷燬實例(好比管理學院首頁頁面緩存)。 二、避免對資源的多重佔用(好比寫文件操做)。框架

缺點:ui

沒有接口,不能繼承,與單一職責原則衝突,一個類應該只關心內部邏輯,而不關心外面怎麼樣來實例化。atom

單例模式你們在iOS中用的比較多了,見的也比較多了,好比Cocoa Touch 框架中使用的單例 1. UIApplication 2:NSFileManager,下面我覺的在項目中登陸模塊用到的單例舉例。spa

SSJLoginModel.h 登陸模型code

@interface SSJLoginModel : NSObject

@property (readwrite, nonatomic, copy) NSString *phone;
@property (readwrite, nonatomic, copy) NSString *password;

@end
複製代碼

SSJLoginModel.m 登陸模型對象

@interface SSJLoginModel ()<NSSecureCoding>

@end

@implementation SSJLoginModel

+ (BOOL)supportsSecureCoding {
    return YES;
}

#pragma mark - NSSecureCoding

- (instancetype)initWithCoder:(NSCoder *)decoder {
    if (!self) {
        return nil;
    }
    
    self.phone = [decoder decodeObjectForKey:NSStringFromSelector(@selector(phone))];
    self.password = [decoder decodeObjectForKey:NSStringFromSelector(@selector(password))];
    
    return self;
}

- (void)encodeWithCoder:(NSCoder *)coder {
    [coder encodeObject:self.phone forKey:NSStringFromSelector(@selector(phone))];
    [coder encodeObject:self.password forKey:NSStringFromSelector(@selector(password))];
    
}

@end
複製代碼

SSJLoginManager.m 登陸管理類繼承

@interface SSJLoginManager : NSObject

+ (instancetype)sharedManager;
@property (readwrite, nonatomic, strong) SSJLoginModel *currentModel;

@end
複製代碼

SSJLoginManager.m 登陸管理類接口

@interface SSJLoginManager ()

@property (readwrite, nonatomic, copy) NSString *filepath;

@end

@implementation SSJLoginManager

+ (instancetype)sharedManager
{
    static SSJLoginManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSString *filepath = @"自定義路徑";
        manager = [[SSJLoginManager alloc] initWithPath:filepath];
    });
    return manager;
}


- (instancetype)initWithPath:(NSString *)filepath {
    if (self = [super init]){
        _filepath = filepath;
        [self writeData];
    }
    return self;
}

- (void)setCurrentModel:(SSJLoginModel *)currentModel {
    _currentModel = currentModel;
    [self saveData];
}

- (void)writeData {
    NSString *filepath = [self filepath];
    if ([[NSFileManager defaultManager] fileExistsAtPath:filepath]) {
        id object = [NSKeyedUnarchiver unarchiveObjectWithFile:filepath];
        _currentModel = [object isKindOfClass:[SSJLoginModel class]] ? object : nil;
    }
}

- (void)saveData {
    NSData *data = [NSData data];
    if (_currentModel) {
        data = [NSKeyedArchiver archivedDataWithRootObject:_currentModel];
    }
    [data writeToFile:[self filepath] atomically:YES];
}


@end
複製代碼

優秀之處:

全部的實現細節都包括在.m文件中,調用者只須要操做currentModel就能夠實現數據的本地化

相關文章
相關標籤/搜索