🏆 作者简介,愚公搬代码 🏆《头衔》:华为云特约编辑,华为云云享专家,华为开发者专家,华为产品云测专家,CSDN博客专家,阿里云专家博主,腾讯云优秀博主,掘金优秀博主,51CTO博客专家等。 🏆《近期荣誉》:2022年CSDN博客之星TOP2,2022年华为云十佳博主等。
🏆《博客内容》:.NET、Java、Python、Go、Node、前端、IOS、Android、鸿蒙、Linux、物联网、网络安全、大数据、人工智能、U3D游戏、小程序等相关领域知识。
🏆🎉欢迎 👍点赞✍评论⭐收藏
设计模式(Design Pattern)是软件开发领域的宝贵经验,是多人反复借鉴和广泛应用的代码设计指导。它们是一系列经过分类和归纳的代码组织方法,旨在实现可重用性、可维护性和可理解性。使用设计模式,我们能够编写高质量的代码,使其更易于他人理解,并提供了代码可靠性的保证。
毫无疑问,设计模式对个人、团队和整个系统都带来了显著的益处。它们将代码开发提升到工程化水平,为软件工程构建提供了坚实的基础,就如同大厦的一块块精巧的砖石一样。在项目中明智地应用设计模式可以完美地解决各种复杂问题。每种设计模式都有相应的原理和最佳实践,它们描述了我们日常开发中不断遇到的问题,以及这些问题的核心解决方法。正是因为这种实用性和通用性,设计模式才能在软件开发中广泛地得以应用。设计模式是构建稳健、可扩展和可维护软件的关键工具,为开发者们提供了解决问题的智慧和指导。
备忘录模式属于行为型设计模式,它的主要目的是在不破坏对象封装性的前提下,捕获对象的内部状态,并在对象之外保存这个状态。这样,我们可以随时将对象还原到之前保存的状态,就好像提供了一种“后悔药”的机制。
备忘录模式的关键点在于它允许我们记录对象的状态快照,以便将来可以恢复它们。这对于需要撤销、重做或历史记录功能的应用程序特别有用。
备忘录模式提供了一种有效的方式来管理对象状态的历史记录,使我们能够在需要时轻松地回滚到先前的状态,从而增强了系统的可维护性和灵活
备忘录模式(Memento Pattern)中的原发器(Originator)是一个重要的概念,它代表了需要被保存状态的对象。原发器在备忘录模式中的作用如下:
createMemento()
)来实现。restoreFromMemento(Memento memento)
),原发器可以将自己的状态恢复为备忘录所记录的状态。在备忘录模式中,原发器与备忘录(Memento)和负责管理备忘录的管理者(Caretaker)一起协作,以实现状态的保存和恢复功能。原发器的关键作用是允许状态的有效管理和封装,同时保持对象的封装性。这对于需要维护对象历史状态的应用程序非常有用。
备忘录模式(Memento Pattern)中的备忘录(Memento)是一个重要的概念,它用于保存原发器(Originator)对象的内部状态,并且可以在需要时将原发器恢复到之前保存的状态。备忘录在该模式中的作用如下:
备忘录在备忘录模式中充当了状态的存储器和管理器的角色,它允许原发器保存和恢复状态,提供了一种有效的方式来处理对象状态的历史记录,从而增强了系统的可
备忘录模式(Memento Pattern)中的备忘录管理者(Caretaker)是一个重要的概念,它负责管理备忘录(Memento)对象,主要作用如下:
备忘录管理者在备忘录模式中扮演了关键的角色,它允许原发器保存状态历史记录、支持撤销和重做操作,同时维护备忘录的封装性。备忘录管理者与原发器和备忘录之间形成了协作,以实现状态的有效管理和恢复。这有助于增强系统的可维护性和用户体验。
命名空间MementoPattern中包含Memento备忘录类,Caretaker管理者类,象棋Chessman类。本案例将向大家演示如何撤销或重做对象棋位置的修改操作。本案例使用栈以支持多次撤销,并且重做支持前1次的多次撤销。本案例不支持重新设置棋子位置时所产生的分支。
public partial class Chessman {
private Point _position;
private Caretaker _caretaker = null;
public Point Position {
get => _position;
set {
_position = value;
_caretaker.Memento.Position = value; Console.WriteLine(
String.Format(Const.POSITION_INFO, _position.X, _position.Y));
}
}
public Chessman() : this(new Point(0, 0)) {
}
public Chessman(Point point) {
_caretaker = new Caretaker(new Memento());
Position = point;
}
}
象棋棋子类Chessman,内部维持棋子的位置,在设置棋子位置时将信息保存到管理者所管理的备忘录中。
public partial class Chessman {
public Chessman Undo(int step) {
try {
Console.WriteLine(Const.ARROW_LEFT);
Console.WriteLine($"Undo({step})!");
this._position = _caretaker.Memento.Undo(step);
Console.WriteLine(
String.Format(Const.POSITION_INFO, _position.X, _position.Y));
Console.WriteLine(Const.ARROW_RIGHT);
return this;
} catch(Exception ex) {
Console.WriteLine(ex.Message);
Console.WriteLine(Const.ARROW_RIGHT);
return this;
}
}
public Chessman Redo() {
try {
Console.WriteLine(Const.ARROW_LEFT);
Console.WriteLine("Redo()!");
this._position = _caretaker.Memento.Redo();
Console.WriteLine(
String.Format(Const.POSITION_INFO, _position.X, _position.Y));
Console.WriteLine(Const.ARROW_RIGHT);
return this;
} catch(Exception ex) {
Console.WriteLine(ex.Message);
Console.WriteLine(Const.ARROW_RIGHT);
return this;
}
}
}
象棋棋子类Chessman的第2部分(partial),支持按步数撤销位置,并且支持重做命令。
public partial class Memento {
private Point _position;
public Point Position {
get => _position;
set {
_position = value;
_history.Push(new RedoInfo { Position = value });
_redoList.Clear();
}
}
public Memento() {
_history = new Stack<RedoInfo>();
_redoList = new Stack<RedoInfo>();
}
private Stack<RedoInfo> _history = null;
private Stack<RedoInfo> _redoList = null;
public Point Undo(int step) {
int totalCount = 0;
List<string> temp = new List<string>();
foreach(var item in _history) {
if(string.IsNullOrWhiteSpace(item.GUID)) {
totalCount++;
} else {
if(!temp.Contains(item.GUID)) {
totalCount++;
temp.Add(item.GUID);
}
}
}
if(step >= totalCount) {
throw new InvalidOperationException("Too much steps!");
}
var guid = Guid.NewGuid().ToString("B");
for(int i = 1; i <= step; i++) {
Undo(guid);
}
return _position;
}
}
备忘录类Memento,内部维持对位置的引用并用2个栈分别管理历史和重做数据。
public partial class Memento {
private void UndoLoop(string guid) {
var history = _history.Pop();
history.GUID = guid;
_redoList.Push(history);
_position = _history.Peek().Position;
}
private void Undo(string guid) {
var temp = _history.Peek().GUID;
if(string.IsNullOrWhiteSpace(temp)) {
UndoLoop(guid);
} else {
while(_history.Peek().GUID == temp) {
UndoLoop(guid);
}
}
}
public Point Redo() {
if(_redoList.Count == 0) {
throw new InvalidOperationException("You can not redo now!");
}
var guid = _redoList.Peek().GUID;
while(_redoList.Count != 0 && _redoList.Peek().GUID == guid) {
_history.Push(_redoList.Pop());
_position = _history.Peek().Position;
}
return _position;
}
}
备忘录类Memento的第2部分(partial),包含了按步数撤销和重做的具体逻辑。
public class Caretaker {
public Memento Memento { get; set; }
public Caretaker(Memento memento) {
Memento = memento;
}
}
管理者Caretaker类,管理者负责维持备忘录。
public class RedoInfo {
public Point Position { get; set; }
public string GUID { get; set; }
}
重做RedoInfo类,按GUID的值判断是否是同一“批次”被撤销的。
public class Const {
public const string POSITION_INFO = "Current position is ({0},{1})!";
public const string ARROW_LEFT = "<---------------------------";
public const string ARROW_RIGHT = "--------------------------->";
}
常量类Const,维护一些本案例中经常用到的字符串。在实际开发过程中不应当有此类,应该将相应的常量放在具体要使用的类中。2017年,阿里发布《阿里巴巴Java开发手册》,其中有一节提到此准则,所有使用面向对象编程语言的开发人员都应当遵从。
public class Program {
private static Chessman _chessman = null;
public static void Main(string[] args) {
_chessman = new Chessman(new Point(1, 10));
_chessman.Position = new Point(2, 20);
_chessman.Position = new Point(3, 30);
_chessman.Position = new Point(4, 40);
_chessman.Position = new Point(5, 50);
_chessman.Position = new Point(9, 40);
_chessman.Undo(1)
.Undo(2)
.Undo(1)
.Redo()
.Redo()
.Redo()
.Redo()
.Redo()
.Undo(6)
.Undo(5)
.Undo(4);
Console.ReadKey();
}
}
以上是调用方的代码演示,撤销和重做方法经过特殊处理以支持方法链。以下是这个案例的输出结果:
Current position is (1,10)!
Current position is (2,20)!
Current position is (3,30)!
Current position is (4,40)!
Current position is (5,50)!
Current position is (9,40)!
<---------------------------
Undo(1)!
Current position is (5,50)!
--------------------------->
<---------------------------
Undo(2)!
Current position is (3,30)!
--------------------------->
<---------------------------
Undo(1)!
Current position is (2,20)!
--------------------------->
<---------------------------
Redo()!
Current position is (3,30)!
--------------------------->
<---------------------------
Redo()!
Current position is (5,50)!
--------------------------->
<---------------------------
Redo()!
Current position is (9,40)!
--------------------------->
<---------------------------
Redo()!
You can not redo now!
--------------------------->
<---------------------------
Redo()!
You can not redo now!
--------------------------->
<---------------------------
Undo(6)!
Too much steps!
--------------------------->
<---------------------------
Undo(5)!
Too much steps!
--------------------------->
<---------------------------
Undo(4)!
Current position is (1,10)!
--------------------------->
备忘录模式(Memento Pattern)具有许多优点,使其成为一种有用的设计模式。以下是备忘录模式的一些主要优点:
备忘录模式提供了一种有效的方式来管理对象状态的历史记录,增强了系统的可维护性、灵活性和用户体验。它在需要保存和恢复对象状态的情况下非常有用,特别是在需要支持撤销和重做操作的应用程序中。
备忘录模式(Memento Pattern)虽然有许多优点,但也存在一些缺点:
总的来说,备忘录模式在一些场景下可以提供有力的支持,但在使用时需要权衡其优缺点,确保选择合适的设计模式来解决特定的问题。备忘录模式特别适用于
备忘录模式(Memento Pattern)适用于以下场景:
备忘录模式在需要保存和管理对象状态历史记录,支持撤销和重做操作,或实现历史记录功能的场景中非常有用。它有助于提高应用程序的可维护性和用户体验,同时保护对象的封装