跟我一起学“仓颉”设计模式-备忘录模式练习题
本章为大家详细的介绍了仓颉设计模式中备忘录模式练习题的内容。
·
目录
一、练习题
1. 模拟网游玩家在“牺牲”后,返回先前的复活点场景。
类图

核心代码
package DesignPattern.memento
public class Player {
public Player(var name: String, public var x: Int64, public var y: Int64) {}
public func save() {
return PlayMemento(this.name, this.x, this.y)
}
public func restore(playerMemento: PlayMemento) {
this.name = playerMemento.name
this.x = playerMemento.x
this.y = playerMemento.y
println("玩家${this.name}死亡, 返回前一个位置: (${this.x}, ${this.y})")
}
public func show() {
println("玩家${this.name}当前位置为: (${this.x}, ${this.y})")
}
}
// 备忘录类
public class PlayMemento {
public PlayMemento(var name: String, var x: Int64, var y: Int64) {}
}
// 负责人
public class Director {
public Director(public var playerMemento: PlayMemento) {}
}
测试代码
package DesignPattern
import DesignPattern.memento.*
main(): Int64 {
let player = Player("常长老", 55, 99)
let director = Director(player.save())
player.show()
player.x = 45
player.y = 50
player.show()
// 保存状态
director.playerMemento = player.save()
player.x = -90
player.show()
player.restore(director.playerMemento)
return 0
}
二、小结
本章为大家详细的介绍了仓颉设计模式中备忘录模式练习题的内容,下一章,为大家带来观察者模式的内容。最后,创作不易,如果大家觉得我的文章对学习仓颉设计模式有帮助的话,就动动小手,点个免费的赞吧!收到的赞越多,我的创作动力也会越大哦,谢谢大家🌹🌹🌹!!!
更多推荐



所有评论(0)