C# 备忘录模式通俗解析
备忘录模式是一种行为设计模式,它允许在不破坏对象封装的前提下,捕获并外部化对象的内部状态,以便稍后可以恢复到该状态。
举个生活例子
想象你在玩电子游戏时的"存档/读档"功能:
- 你玩游戏到一个关键时刻(存档点)
- 系统保存当前游戏状态(角色位置、装备、生命值等)
- 你继续游戏,可能失败或想尝试不同策略
- 可以随时回滚到之前保存的状态(读档)
备忘录模式就是实现这种功能的编程方式,让对象可以保存自己的状态到备忘录对象中,并能从备忘录恢复状态。
C#代码示例
// 游戏角色类(需要保存状态的原发器)
public class GameCharacter
{
public string Name { get; set; }
public int Level { get; set; }
public int Health { get; set; }
public string CurrentWeapon { get; set; }
public Position Position { get; set; }
// 创建备忘录(存档)
public CharacterMemento Save()
{
return new CharacterMemento(Level, Health, CurrentWeapon, Position);
}
// 从备忘录恢复(读档)
public void Restore(CharacterMemento memento)
{
Level = memento.Level;
Health = memento.Health;
CurrentWeapon = memento.CurrentWeapon;
Position = memento.Position;
Console.WriteLine($"角色已恢复到: 等级{Level}, 生命{Health}, 武器{CurrentWeapon}, 位置({Position.X},{Position.Y})");
}
// 显示当前状态
public void Display()
{
Console.WriteLine($"当前状态: {Name} 等级{Level}, 生命{Health}, 武器{CurrentWeapon}, 位置({Position.X},{Position.Y})");
}
}
// 位置类
public class Position
{
public int X { get; set; }
public int Y { get; set; }
public Position(int x, int y)
{
X = x;
Y = y;
}
}
// 备忘录类(存储角色状态)
public class CharacterMemento
{
public int Level { get; }
public int Health { get; }
public string CurrentWeapon { get; }
public Position Position { get; }
public CharacterMemento(int level, int health, string weapon, Position position)
{
Level = level;
Health = health;
CurrentWeapon = weapon;
Position = position;
}
}
// 存档管理器(负责管理备忘录)
public class SaveGameManager
{
private Dictionary<string, CharacterMemento> _saves = new Dictionary<string, CharacterMemento>();
public void AddSave(string saveName, CharacterMemento memento)
{
_saves.Add(saveName, memento);
Console.WriteLine($"游戏已存档: {saveName}");
}
public CharacterMemento GetSave(string saveName)
{
if (_saves.TryGetValue(saveNa