备忘录模式:在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复原先保存的状态。
优点:能很好的封装内部状态,避免客户修改。
缺点:如果内部数据比较多的话,会造成难以维护。
总结:备忘录模式适合比较小的数据备份,与其他模式一起使用效果会好很多。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
// // main.m // Memento // // Created by GameRisker on 16/9/17. // Copyright (c) 2016年 GameRisker. All rights reserved. // #import "Caretaker.h" #import "Memento.h" #import "Originator.h" #import <Foundation/Foundation.h> int main(int argc, const char *argv[]) { @autoreleasepool { Originator *originator = [[Originator alloc] init]; Caretaker *caretaker = [[Caretaker alloc] init]; Memento *memento = [originator CreateMemento]; [caretaker SetMemento:memento]; originator.state = @"dead"; memento = [caretaker GetMemento]; [originator SetMemento:memento]; NSLog(@"Originator state is : %@", originator.state); } return 0; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// // Originator.h // Memento // // Created by GameRisker on 16/9/17. // Copyright (c) 2016年 GameRisker. All rights reserved. // #import <Foundation/Foundation.h> @interface Originator : NSObject @property(strong, nonatomic) NSString *state; - (void)SetMemento:(Memento *)men; - (Memento *)CreateMemento; @end |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
// // Originator.m // // // Created by GameRisker on 16/9/17. // // #import "Memento.h" #import "Originator.h" #import <Foundation/Foundation.h> @implementation Originator : NSObject - (instancetype)init { if (self = [super init]) { self.state = @"born"; } return self; } - (void)SetMemento:(Memento *)men { self.state = men.state; } - (Memento *)CreateMemento { Memento *men = [[Memento alloc] init]; men.state = self.state; return men; } @end |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// // Caretaker.h // Memento // // Created by GameRisker on 16/9/17. // Copyright (c) 2016年 GameRisker. All rights reserved. // #import "Memento.h" #import <Foundation/Foundation.h> @interface Caretaker : NSObject @property(strong, nonatomic) Memento *m_memento; - (void)SetMemento:(Memento *)men; - (Memento *)GetMemento; @end |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
// // Caretaker.m // // // Created by GameRisker on 16/9/17. // // #import "Caretaker.h" #import <Foundation/Foundation.h> @implementation Caretaker : NSObject - (void)SetMemento:(Memento *)men { self.m_memento = men; } - (Memento *)GetMemento { return self.m_memento; } @end |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// // Memento.h // Memento // // Created by GameRisker on 16/9/17. // Copyright (c) 2016年 GameRisker. All rights reserved. // #import <Foundation/Foundation.h> @interface Memento : NSObject @property(strong, nonatomic) NSString *state; @end |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// // Memento.m // // // Created by GameRisker on 16/9/17. // // #import "Memento.h" #import <Foundation/Foundation.h> @implementation Memento : NSObject @end |