| 游戏角色有攻击力和防御力,在大战Boss前保存自身的状态(攻击力和防御力),当大战Boss后攻击力和防御力下降,从备忘录对象恢复到大战前的状态 |

| package com.atguigu.memento.game; |
| public class Memento { |
| |
| |
| private int vit; |
| |
| private int def; |
| |
| public Memento(int vit, int def) { |
| super(); |
| this.vit = vit; |
| this.def = def; |
| } |
| |
| public int getVit() { |
| return vit; |
| } |
| |
| public void setVit(int vit) { |
| this.vit = vit; |
| } |
| |
| public int getDef() { |
| return def; |
| } |
| |
| public void setDef(int def) { |
| this.def = def; |
| } |
| |
| } |
| |
| package com.atguigu.memento.game; |
| public class GameRole { |
| |
| private int vit; |
| |
| private int def; |
| |
| |
| public Memento createMemento() { |
| return new Memento(vit, def); |
| } |
| |
| |
| public void recoverGameRoleFromMemento(Memento memento) { |
| this.vit = memento.getVit(); |
| this.def = memento.getDef(); |
| } |
| |
| |
| public void display() { |
| System.out.println("游戏角色当前的攻击力:" + this.vit + " 防御力: " + this.def); |
| } |
| |
| public int getVit() { |
| return vit; |
| } |
| |
| public void setVit(int vit) { |
| this.vit = vit; |
| } |
| |
| public int getDef() { |
| return def; |
| } |
| |
| public void setDef(int def) { |
| this.def = def; |
| } |
| |
| } |
| |
| package com.atguigu.memento.game; |
| |
| public class Caretaker { |
| |
| |
| private Memento memento; |
| |
| |
| |
| |
| |
| public Memento getMemento() { |
| return memento; |
| } |
| |
| public void setMemento(Memento memento) { |
| this.memento = memento; |
| } |
| |
| } |
| |
| package com.atguigu.memento.game; |
| public class Client { |
| |
| public static void main(String[] args) { |
| |
| GameRole gameRole = new GameRole(); |
| gameRole.setVit(100); |
| gameRole.setDef(100); |
| |
| System.out.println("和boss大战前的状态"); |
| gameRole.display(); |
| |
| Caretaker caretaker = new Caretaker(); |
| caretaker.setMemento(gameRole.createMemento()); |
| System.out.println("和boss大战~~~"); |
| gameRole.setDef(30); |
| gameRole.setVit(30); |
| gameRole.display(); |
| System.out.println("大战后,使用备忘录对象恢复到站前"); |
| gameRole.recoverGameRoleFromMemento(caretaker.getMemento()); |
| System.out.println("恢复后的状态"); |
| gameRole.display(); |
| } |
| |
| } |
| 1) 给用户提供了一种可以恢复状态的机制,可以使用户能够比较方便地回到某个历史的状态 |
| 2) 实现了信息的封装,使得用户不需要关心状态的保存细节 |
| 3) 如果类的成员变量过多,势必会占用比较大的资源,而且每一次保存都会消耗一定的内存, 这个需要注意 |
| 4) 适用的应用场景:1、后悔药。 2、打游戏时的存档。 3、Windows 里的 ctri + z。 4、IE 中的后退。 4、数据库的事务管理 |
| 5) 为了节约内存,备忘录模式可以和原型模式配合使用 |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?