-
Notifications
You must be signed in to change notification settings - Fork 1
/
MementoPattern.java
58 lines (45 loc) · 1.33 KB
/
MementoPattern.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package DesignPatterns.BehaviouralDesignPattern;
import java.util.ArrayList;
import java.util.List;
public class MementoPattern {
public static void main(String[] args) {
List<Memento> list = new ArrayList<>();
Life life = new Life();
life.setTime("1000 BC");
list.add(life.saveToMemento());
life.setTime("2000 BC");
list.add(life.saveToMemento());
life.setTime("3000 BC");
list.add(life.saveToMemento());
System.out.println("restoring to old time" );
life.restoreFromMomento(list.get(0));
System.out.println("new time of the life is "+life.getTime() );
}
}
class Life{
private String time;
public Memento saveToMemento(){
System.out.println("creating a new memento for the time "+time);
return new Memento(time);
}
public void restoreFromMomento(Memento memento){
System.out.println("restoring from Memento to time "+memento.getTime());
time = memento.getTime();
}
public void setTime(String time) {
System.out.println("Time restored ");
this.time = time;
}
public String getTime() {
return time;
}
}
class Memento{
private String time;
public Memento(String time) {
this.time = time;
}
public String getTime() {
return time;
}
}