一个用命令模式写的支持撤销重做的小工具

//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方法进行撤销/重做操作。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值