Undo and redo

Report a typo

In this task, you must implement the undo and redo methods in the Caretaker class using two ArrayDeque collections available in that class.

The required class structure is already set up: the beforeValueChanged method, which is called by the client before modifying the value in the Originator instance, takes care of tracking the changes in the Originator instance, populates undoStack and clears redoStack.

The logic of the methods you must implement is quite simple: undo must replace the value in originator with the most recent value stored in undoStack, and redo must reverse the most recent action of the undo method.

Write a program in Java 17
import java.util.*;

class Originator<T> {
private T value;

public void setValue(T value) {
this.value = value;
}

public void printValue() {
System.out.println(value);
}

public Memento<T> getMemento() {
return new Memento<>(value);
}

public void setMemento(Memento<T> memento) {
this.value = memento.value;
}

static class Memento<T> {
private final T value;

private Memento(T value) {
this.value = value;
}
}
}

class Caretaker<T> {
private final Originator<T> originator;
private final Deque<Originator.Memento<T>> undoStack = new ArrayDeque<>();
private final Deque<Originator.Memento<T>> redoStack = new ArrayDeque<>();

Caretaker(Originator<T> originator) {
___

Create a free account to access the full topic