转自@H_301_5@ Swift设计模式
原文@H_301_5@ Design-Patterns-In-Swift
// 备忘录模式// 百度百科:在不破坏封闭的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态// 设计模式分类:行为型模式import Foundationtypealias Memento = Dictionary<NSObject,AnyObject>let DPMementoKeyChapter = "com.valve.halflife.chapter"let DPMementoKeyWeapon = "com.valve.halflife.weapon"let DPMementoGameState = "com.valve.halflife.state"/// 游戏状态class GameState { var chapter: String = "" var weapon: String = "" /** 生成游戏存档 - returns: 存档 */ func toMemento() -> Memento { return [ DPMementoKeyChapter:chapter,DPMementoKeyWeapon:weapon ] } /** 恢复游戏存档 - parameter memento: 存档 */ func restoreFromMemento(memento: Memento) { chapter = memento[DPMementoKeyChapter] as? String ?? "n/a" weapon = memento[DPMementoKeyWeapon] as? String ?? "n/a" }}/** 存档点 */enum CheckPoint { /** 保存存档 - parameter memento: 存档 - parameter keyname: 存档名 */ static func saveState(memento: Memento,keyname: String = DPMementoGameState) {// let defaults = NSUserDefaults.standardUserDefaults()// defaults.setobject(memento,forKey: keyname)// defaults.synchronize() DB.set(keyname,obj: memento) } /** 读取存档 - parameter keyname: 存档名 - returns: 存档 */ static func restorePrevIoUsstate(keyname keyname: String = DPMementoGameState) -> Memento {// let defaults = NSUserDefaults.standardUserDefaults()// // return defaults.objectForKey(keyname) as? Memento ?? Memento() let m = DB.get(keyname) return m as? Memento ?? Memento() }}class DB { static var dict:Dictionary<String,AnyObject> = [:] class func set(key: String,obj: AnyObject) { dict[key] = obj } class func get(key: String) -> AnyObject? { return dict[key] }}func printGameStateInfo(state: GameState) -> VoID { print("当前游戏状态:[chapter = \(state.chapter),weapon = \(state.weapon)]")}var gameState = GameState()gameState.restoreFromMemento(CheckPoint.restorePrevIoUsstate()) // 新游戏printGameStateInfo(gameState)gameState.chapter = "第一章 新手上路"gameState.weapon = "木剑"CheckPoint.saveState(gameState.toMemento()) // 第一个存档printGameStateInfo(gameState)gameState.chapter = "第二章 冒险开始"gameState.weapon = "铜剑"gameState.restoreFromMemento(CheckPoint.restorePrevIoUsstate()) // 恢复存档printGameStateInfo(gameState)gameState.chapter = "第三章 挑战魔龙"gameState.weapon = "铁剑"CheckPoint.saveState(gameState.toMemento(),keyname: "gameState2") // 第二个存档printGameStateInfo(gameState)gameState.chapter = "最后章 最终之战"gameState.weapon = "圣剑"CheckPoint.saveState(gameState.toMemento()) // 覆盖第一个存档printGameStateInfo(gameState)gameState.restoreFromMemento(CheckPoint.restorePrevIoUsstate(keyname: "gameState2")) // 加载第二个存档printGameStateInfo(gameState)总结
以上是内存溢出为你收集整理的Swift设计模式之备忘录模式全部内容,希望文章能够帮你解决Swift设计模式之备忘录模式所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)