forked from john-bai/DesignPatterns
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMemento.java
More file actions
73 lines (55 loc) · 1.17 KB
/
Copy pathMemento.java
File metadata and controls
73 lines (55 loc) · 1.17 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package designpatterns;
import java.awt.Point;
import java.util.Stack;
/**
*
* @author jtherrell
*/
class Graphix {
private Point position;
public Graphix(Point position) {
this.position = position;
}
public void move(Point delta) {
position.x += delta.x;
position.y += delta.y;
}
public GraphixMemento createMemento() {
return new GraphixMemento(new Point(position.x, position.y));
}
public void setMemento(GraphixMemento memento) {
position = memento.state();
}
public Point position() {
return position;
}
}
class GraphixMemento{
private Point position;
public GraphixMemento(Point position) {
this.position = position;
}
public Point state() {
return position;
}
}
class MoveCommand {
private Graphix target;
private Stack<GraphixMemento> state;
public MoveCommand (Graphix target) {
this.target = target;
state = new Stack<GraphixMemento>();
}
public void execute(Point delta) {
state.push(target.createMemento());
target.move(delta);
}
public void unexecute() {
if(!state.empty())
target.setMemento(state.pop());
}
}