技术开发 频道

C#中使用备忘录模式实现Undo/Redo

  步骤4

  下面的Caretaker类将memento (state)保存在两个栈中。Undo栈为Undo操作保存Memento (state),而Redo栈为/Redo操作保存Memento (state)。

Collapse  Copy Code
  
class Caretaker
    {
        
private Stack<Memento> UndoStack = new Stack<Memento>();
        
private Stack<Memento> RedoStack = new Stack<Memento>();

        
public Memento getUndoMemento()
        {
            
if (UndoStack.Count >= 2)
            {
                RedoStack.Push(UndoStack.Pop());
                
return UndoStack.Peek();
            }
            
else
                
return null;
        }
        
public Memento getRedoMemento()
        {
            
if (RedoStack.Count != 0)
            {
                Memento m
= RedoStack.Pop();
                UndoStack.Push(m);
                
return  m;
            }
            
else
                
return null;
        }
        
public void InsertMementoForUndoRedo(Memento memento)
        {
            
if (memento != null)
            {
                UndoStack.Push(memento);
                RedoStack.Clear();
            }
        }
        
public bool IsUndoPossible()
        {
            
if (UndoStack.Count >= 2)
            {
                
return true;
            }
            
else
                
return false;

        }
        
public bool IsRedoPossible()
        {
            
if (RedoStack.Count != 0)
            {
                
return true;
            }
            
else
                
return false;
        }

    }
1
相关文章