Undo,Redoの実装って何十回もやってる気がする


undo,redoundo,redo 
http://twitter.com/youpychan/status/994486992  




undo,redo
 http://twitter.com/youpychan/status/994636764  




Undo,Redo


Unod,Redo
使UndoRedo
Undo,Redo


使

(DataModelsetText(string text)Text
ICommandICommand


public interface ICommand {
    public CommandType getCommandType();
    public DataModel getDataModel();
}


CommandTypeDataModel


TextUPDATE


public class UpdateCommand implements ICommand {
    private DataModel mModel;
    private String mPrevText;
    private String mNewText;

    public UpdateCommand(DataModel model, String prevText, String newText) {
        mModel = model;
        mPrevText = prevText;
        mNewText = newText;
    }

    public CommandType getCommandType() {
        return CommandType.UPDATE;
    }

    public DataModel getDataModel() {
        return mModel;
    } 

    public String getPrevText() {
        return mPrevText;
    }

    public String getNewText() {
        return mNewText;
    }
}


public class CommandInvoker {
    public void undo(ICommand command) {
        switch (command.getCommandType()) {
             case CommandType.UPDATE:
                 UpdateCommand updateCmd = (UpdateCommand)command;
                 updateCmd.getDataModel().setText(updateCmd.getPrevText());
                 break;
             ...
        }
    }
}

undo()redo()invoke()


twitter
使


使ICommand


public interface ICommand {
    public void invoke();
    public void undo();
    public void redo();
}


UpdateCommand


public class UpdateCommand implements ICommand {
    private DataModel mModel;
    private String mPrevText;
    private String mNewText;

    public UpdateCommand(DataModel model, String newText) {
        mModel = model;
        mPrevText = prevText;
        mNewText = newText;
    }

    public void invoke() {
        mPrevText = mModel.getText();
        mModel.setText(mNewText);
    }

    public void undo() {
        mModel.setText(mPrevText);
    }

    public void redo() {
        mModel.setText(mNewText);
    }
}

ICommandinvoke(),undo(),redo()


C#使


ICommand使Command
public class Command
{
     Action Invoke;
     Action Undo;
     Action Redo;
}



public class CommandInvoker
{
     public ICommand createUpdateCommand(DataModel model, string newText)
     {
          string prevText = null;
          Command cmd = new Command();
          cmd.Invoke = () =>
          {
               prevText = model.Text;
               model.Text = newText;
          };
 
          cmd.Updo = () =>
          {
               model.Text = prevText;
          };

          cmd.Redo = () =>
          {
               model.Text = newText;
          };

          return cmd;
     }
}

Java使final
便



Undo,Redo