Java: методы Undo и Redo для класса Rectangle [дубликат]

Oct 16 2020

У меня есть собственный класс Rectangle:

public class Rectangle () {
      private int height, width, x, y;
      private Color color;
      
      public Rectangle () {
           this.height = null;
           this.width = null;
           this.x = null;
           this.y = null;
           this.color = null;
      }
      
      public void setHeight(int h) { this.height = h; }

      public void setWidth(int w) { this.width = w; }
      
      public void setX(int x) { this.x = x; }
      
      public void setY(int y) { this.y = y; }
       
      public void setColor(Color c) { this.color = c; }

      public int getWidth() { return this.width; }
      
      public int getHeight() { return this.height; }

      public int getX() { return this.x; }
      
      public int getY() { return this.y; }
      
      public Color getColor() { return this.color; }
      
      public void undo() {   }

      public void redo() {   }

}

Как мне реализовать функции отмены и повтора для этого класса таким образом, чтобы он мог вернуть прямоугольник в его предыдущее состояние без упоминания пользователем того, какой метод использовался последним. У меня есть смутное представление об использовании стека, но я застрял в том, как его кодировать. Мой второй вопрос: я не уверен, верен ли мой конструктор, я инициализирую все до нуля, не задавая никаких параметров, потому что я хочу, чтобы вместо этого люди использовали геттеры / сеттеры. Пожалуйста помоги.

Ответы

1 Harkal Oct 16 2020 at 12:37

вы можете сохранить состояние в массиве и восстановить из него прямоугольник

public class Rectangle () {
    
    private states: List<Rectangle> = new ArrayList(); // we save the state of rectangle on every update to any property
    private int stateIndex = 0; // this is the index of the state which is active on this rectangle
    
    private int height, width, x, y;
    private Color color;
    
    public Rectangle () {
       this.height = null;
       this.width = null;
       this.x = null;
       this.y = null;
       this.color = null;
    }
    
    public void setHeight(int h) { 
        this.stateIndex = states.size() + 1; // we ll increase one in state index as new state is added to the states
        this.height = h; 
        this.states.add(this); // add the state after you set the value of any property
    }
    
    public void undo() { 
        if(this.stateIndex > 0){ // only undo when there is state available before the current state
            this.stateIndex--; // reduce the current index by one
            this.height = this.states.get(stateIndex).height; // set the properties from state
            ...
        }
    }
    
    public void redo() {    
        if(this.stateIndex < states.size()){ // can go more the available states in cache
            this.stateIndex++; // increase the current state index
            this.height = this.states.get(stateIndex).height; // update the values of the properties
            ...
        }
    }

}