ios 设计模式备忘录(1)


适用场景:用来进行实现缓存 或 进行一些状态恢复撤销的功能

1.创建管理中心 实现了具体的存储方法

代码.h文件

#import
#import "MenmentoCenterProtocol.h"

@interface MementoCenter : NSObject
+(void)saveMementoObject:(id)object withKey:(NSString *)key;
+(id)mementoObjectWithKey:(NSString *)key;


.m文件

#import "MementoCenter.h"

@implementation MementoCenter
+(void)saveMementoObject:(id)object withKey:(NSString *)key
{
    NSParameterAssert(object);
    NSParameterAssert(key);
    id data=[object currentState];
    [[NSUserDefaults standardUserDefaults] setObject:data forKey:key];
}
+(id)mementoObjectWithKey:(NSString *)key
{
    NSParameterAssert(key);
     id caheData=[[NSUserDefaults standardUserDefaults] objectForKey:key];
    return caheData;
}
@end

2.写协议文件 用来提高可读性 和代码维护 协议里具体标注了 要实现缓存的具体的类需要实现的方法

#import

//统一存储规范  fastCoder
@protocol MenmentoCenterProtocol
@required
-(id)currentState;
-(void)recoverFromState:(id)state;

@end

.m文件

#import
#import "MementoCenter.h"
@interface NSObject (MementCenter)
-(void)saveStateWithKey:(NSString *)key;
-(void)recoverStateWithKey:(NSString *)key;
@end


3.在具体需要实现缓存的类中实现 协议的方法

#import "Apple.h"

@implementation Apple
-(id)currentState
{
    return @{@"name":self.name,@"age":self.age};
}
-(void)recoverFromState:(id)state
{
    NSDictionary *data=state;
    self.name=data[@"name"];
    self.age=data[@"age"];
}

4.为了方便 创建个对象的父类的 类别 categoey

导入你的缓存中心

#import
#import "MementoCenter.h"
@interface NSObject (MementCenter)
-(void)saveStateWithKey:(NSString *)key;
-(void)recoverStateWithKey:(NSString *)key;



#import "NSObject+MementCenter.h"

@implementation NSObject (MementCenter)
-(void)saveStateWithKey:(NSString *)key
{
    id obj=(id)self;
    if ([obj respondsToSelector:@selector(currentState)]) {
        [MementoCenter saveMementoObject:obj withKey:key];

    }
}
-(void)recoverStateWithKey:(NSString *)key
{
   id state= [MementoCenter mementoObjectWithKey:key];
    id obj=(id) self;
    if ([obj respondsToSelector:@selector(recoverFromState:)]) {
        [obj recoverFromState:state];
    }
}

最后就可以使用了


你可能感兴趣的:(ios,设计模式,缓存)