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;
            }
        }
  • 相关阅读:
    关于sql json数据的处理
    时间函数strtotime的强大
    /usr/bin/install: cannot create regular file `/usr/local/jpeg6/include/jconfig.h'
    linux安装php7.2.7
    关于sql时间方面的处理
    关于centos防火墙的一些问题
    linux 安装ssl 失败原因
    linux安装php7.2.7
    拾取坐标和反查询接口api
    【转】通过点击获取地址等信息、可以传值
  • 原文地址:https://www.cnblogs.com/chenyishi/p/9128686.html
Copyright © 2011-2022 走看看