Memento.java
public class Memento {
private String currentText;
public Memento(String text){
this.currentText = text;
}
public String getCurrentText(){
return currentText;
}
}
CareTaker.java
import java.util.ArrayList;
public class CareTaker {
private ArrayListmementoList;
public CareTaker(){
mementoList = new ArrayList();
}
public void push(Memento memento){
mementoList.add(memento);
}
public Memento pop(){
Memento memento = mementoList.get(mementoList.size()-1);
mementoList.remove(mementoList.size()-1);
return memento;
}
}
NotePad.java
public class NotePad {
String currentText;
private CareTaker careTaker;
public NotePad(){
careTaker = new CareTaker();
currentText="";
}
public String getCurrentText() {
return currentText;
}
public void setCurrentText(String currentText) {
this.currentText = currentText;
}
public void appendString(String message){
this.currentText+=message;
}
public Memento saveStateToMemento(){
return new Memento(currentText);
}
public int hashCode() {
return careTaker.hashCode();
}
public String toString() {
return careTaker.toString();
}
public boolean equals(Object arg0) {
return careTaker.equals(arg0);
}
public void save(){
careTaker.push(new Memento(this.currentText));
}
public void undo(){
Memento memento = careTaker.pop();
this.currentText=memento.getCurrentText();
}
}
MementoPatternDemo.java
import java.util.Scanner;
public class MementoPatternDemo {
public static void main(String[] args) {
//create the notepad class
NotePad notepad = new NotePad();
Scanner sc = new Scanner(System.in);
//enter the string
System.out.println("enter the string");
notepad.appendString(sc.next());
notepad.save();
System.out.println("current Text saved ::"+notepad.getCurrentText());
//enter next string
System.out.println("enter the string");
notepad.appendString(sc.next());
notepad.save();
System.out.println("current Text saved ::"+notepad.getCurrentText());
//enter next string
System.out.println("enter the string");
notepad.appendString(sc.next());
System.out.println("current Text saved ::"+notepad.getCurrentText());
notepad.undo();
System.out.println("after undo 1 current Text saved ::"+notepad.getCurrentText());
notepad.undo();
System.out.println("adter undo 2 current Text saved ::"+notepad.getCurrentText());
}
}
Output
