设计模式-23种设计模式-行为型-备忘录模式
一、备忘录模式介绍
二、备忘录模式引入
需求:
UML类图:
代码实现(Java):
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; } }
import java.util.ArrayList; import java.util.HashMap; //守护者对象, 保存游戏角色的状态 public class Caretaker { //如果只保存一次状态 private Memento memento; //对GameRole 保存多次状态 //private ArrayList<Memento> mementos; //对多个游戏角色保存多个状态 //private HashMap<String, ArrayList<Memento>> rolesMementos; public Memento getMemento() { return memento; } public void setMemento(Memento memento) { this.memento = memento; } }
public class GameRole { private int vit; private int def; //创建Memento ,即根据当前的状态得到Memento public Memento createMemento() { return new Memento(vit, def); } //从备忘录对象,恢复GameRole的状态 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; } }
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 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(); } }
三、备忘录模式注意事项和细节
分类:
DesignPattern
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 没有源码,如何修改代码逻辑?
· NetPad:一个.NET开源、跨平台的C#编辑器