命令模式

命令模式:命令模式属于对象的行为型模式。命令模式是把一个操作或者行为抽象为一个对象中,通过对命令的抽象化来使得发出命令的责任和执行命令的责任分隔开。命令模式的实现可以提供命令的撤销和恢复功能。

UML图:

示例代码:

    interface Command
    {
        void execute();
        void undo();
    }
    public class TextChangedCommand : Command
    {
        private TextBox ctrl;
        private String newStr;
        private String oldStr;

        public TextChangedCommand(TextBox ctrl, String newStr, String oldStr)
        {
            this.ctrl = ctrl;
            this.newStr = newStr;
            this.oldStr = oldStr;
        }

        public void execute()
        {
            this.ctrl.Text = newStr;
            this.ctrl.SelectionStart = this.ctrl.Text.Length;
        }

        public void undo()
        {
            this.ctrl.Text = oldStr;
            this.ctrl.SelectionStart = this.ctrl.Text.Length;
        }
    }
    public partial class Form1 : Form
    {
        Stack<Command> undoStack = new Stack<Command>();
        Stack<Command> redoStack = new Stack<Command>();

        string oldStr = null;
        bool flag = true;

        public Form1()
        {
            InitializeComponent();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            if (flag)
            {
                TextChangedCommand com = new TextChangedCommand((TextBox)textBox1, ((TextBox)textBox1).Text, oldStr);
                undoStack.Push(com);
                oldStr = ((TextBox)textBox1).Text;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (undoStack.Count == 0)
                return;
            flag = false;
            Command com = undoStack.Pop();
            com.undo();
            redoStack.Push(com);
            flag = true;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (redoStack.Count == 0)
                return;
            flag = false;
            Command com = redoStack.Pop();
            com.execute();
            undoStack.Push(com);
            flag = true;
        }
    }
原文地址:https://www.cnblogs.com/chenyishi/p/9128686.html