天天看點

指令模式

指令模式:指令模式屬于對象的行為型模式。指令模式是把一個操作或者行為抽象為一個對象中,通過對指令的抽象化來使得發出指令的責任和執行指令的責任分隔開。指令模式的實作可以提供指令的撤銷和恢複功能。

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;
        }
    }