//gjy
using System.Collections.Generic;
public class UndoRedoTool
{
private Stack<CanUndoRedoCmd> _alreadyDoCmd;
private Stack<CanUndoRedoCmd> _alreadyUndoCmd;
public UndoRedoTool()
{
_alreadyDoCmd = new Stack<CanUndoRedoCmd>();
_alreadyUndoCmd = new Stack<CanUndoRedoCmd>();
}
public void Display(CanUndoRedoCmd cmd)
{
cmd.Display();
_alreadyUndoCmd.Clear();
_alreadyDoCmd.Push(cmd);
}
public void Undo()
{
if (_alreadyDoCmd.Count > 0)
{
CanUndoRedoCmd cmd = _alreadyDoCmd.Pop();
cmd.Undo();
_alreadyUndoCmd.Push(cmd);
}
}
public void Redo()
{
if (_alreadyUndoCmd.Count > 0)
{
CanUndoRedoCmd cmd = _alreadyUndoCmd.Pop();
cmd.Redo();
_alreadyDoCmd.Push(cmd);
}
}
public void UndoAllClear()
{
while (_alreadyDoCmd.Count > 0)
{
Undo();
}
_alreadyUndoCmd.Clear();
}
}
public interface CanUndoRedoCmd
{
void Display();
void Undo();
void Redo();
}
缺点:没有设置撤销重做的数量上限。(说白了,就是懒)
示例:
using System;
public class UndoRedoExample
{
public UndoRedoExample(int initValue)
{
_cmdList = new UndoRedoTool();
TargetValue = initValue;
}
private UndoRedoTool _cmdList;
public int TargetValue { get; private set; }
public void Operate(int changeValue)
{
_cmdList.Display(new ChangeNum(changeValue,UnChangeTarget,DoChangeTarget));
}
public void Undo()
{
_cmdList.Undo();
}
public void Redo()
{
_cmdList.Redo();
}
private void DoChangeTarget(int num)
{
TargetValue += num;
}
private void UnChangeTarget(int num)
{
TargetValue -= num;
}
private class ChangeNum : CanUndoRedoCmd
{
private int _cacheNum;
private Action<int> _unChange;
private Action<int> _doChange;
public ChangeNum(int num,Action<int> unChange,Action<int> doChange)
{
_cacheNum = num;
_unChange = unChange;
_doChange = doChange;
}
public void Display()
{
_doChange(_cacheNum);
}
public void Redo()
{
_doChange(_cacheNum);
}
public void Undo()
{
_unChange(_cacheNum);
}
}
}
示例用法:声明一个UndoRedoExample对象,可以通过Operate方法修改TargetValue的值,通过Undo/Redo方法进行撤销/重做操作。