zoukankan      html  css  js  c++  java
  • 命令模式

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

    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;
            }
        }
  • 相关阅读:
    zech的神秘题库(武汉理工夜莺杯)
    回归第六题
    同余方程
    牛牛选路径(牛客)
    回归第三题
    区间dp复习提高专题
    乘法逆元(线性递推)
    回归第八题
    JAVA启动参数大全之二:非标准参数(转)
    (转)Spring Security 3.1 自定义实例之登陆
  • 原文地址:https://www.cnblogs.com/chenyishi/p/9128686.html
Copyright © 2011-2022 走看看