试图实现撤销/重做,发现这篇文章,我不太理解.的帮助
本文关键字:文章 帮助 实现 发现 重做 | 更新日期: 2023-09-27 18:05:03
在我的应用程序中有一个多维数组,其中可能包含大量数据,因此每次用户更改时完全保存该对象似乎是不可行的。
我读了关于Command模式的文章,最终找到了这篇文章,但我不太理解它。我不确定他的代码示例是如何工作的,也不确定这是否会在我的应用程序中工作。另外,这种"新"方法是否优于GoF模式?
我的应用程序有工具,如画笔和填充工具的工作在当前的文档,我不确定如何最好地实现撤销/重做功能,但我知道保存每个操作对象的状态将不允许无限的撤消和重做,这是我所追求的。我不确定Command模式是否可以在这种上下文中使用,也不确定本文的实现是否可以以及如何工作。
希望有人能详细说明这篇文章,或者解释如何使Command模式适应我的需要。感谢阅读!
创建一个具有三个值(location、oldvalue和newvalue,其中location指向多维数组中的一个元素)和两个方法(undo、redo)的类。在每次操作时,为更改的大数组中的每个元素创建这些对象的数组,并将其推入撤销堆栈。弹出撤销堆栈时,调用undo,然后将其推送到重做堆栈。与重做pop相反。只要记得用新动作清除重做堆栈。
编辑:示例:
public void undo()
{
location = oldvalue;
}
public void redo()
{
location = newvalue;
}
然后是堆栈的例子:
command = undoStack.Pop();
command.undo();
redoStack.Push(command);
只是做了一些调查,让我想到了一些可能的解决方案。最简单的可能是使用堆栈。另一种是使用纪念品图案。但是既然你问了命令模式,这里有一个简单的例子。
这基本上是取自codeprojects的例子。
class Document
{
private List<string> _textArray = new List<string>();
public void Write(string text)
{
_textArray.Add(text);
}
public void Erase(string text)
{
_textArray.Remove(text);
}
public void Erase(int textLevel)
{
_textArray.RemoveAt(textLevel);
}
public string ReadDocument()
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
foreach(string text in _textArray)
sb.Append(text);
return sb.ToString();
}
}
abstract class Command
{
abstract public void Redo();
abstract public void Undo();
}
class DocumentEditCommand : Command
{
private Document _editableDoc;
private string _text;
public DocumentEditCommand(Document doc, string text)
{
_editableDoc = doc;
_text = text;
_editableDoc.Write(_text);
}
override public void Redo()
{
_editableDoc.Write(_text);
}
override public void Undo()
{
_editableDoc.Erase(_text);
}
}
class DocumentInvoker
{
private List<Command> _commands = new List<Command>();
private Document _doc = new Document();
public void Redo( int level )
{
Console.WriteLine( "---- Redo {0} level ", level );
((Command)_commands[ level ]).Redo();
}
public void Undo( int level )
{
Console.WriteLine( "---- Undo {0} level ", level );
((Command)_commands[ level ]).Undo();
}
public void Write(string text)
{
DocumentEditCommand cmd = new
DocumentEditCommand(_doc,text);
_commands.Add(cmd);
}
public string Read()
{
return _doc.ReadDocument();
}
}
使用命令模式
我们对documentinvoker的实例执行两个"操作"(实现我们的命令模式)。
DocumentInvoker instance = new DocumentInvoker ();
instance.Write("This is the original text.");
instance.Write(" Here is some other text.");
现在我们可以撤销这些操作。
instance.Undo(1);
文档中的文本现在将是。
---- Undo 1 level
This is the original text.
现在我们可以重做这个动作
instance.Redo(1);
文本将是。
---- Redo 1 level
This is the original text. Here is some other text.
显然,您需要修改它以满足您的需求。如果您想要更多的解释,请查看文章http://www.codeproject.com/KB/books/DesignPatterns.aspx.