-
Notifications
You must be signed in to change notification settings - Fork 0
/
Controller.java
115 lines (104 loc) · 2.21 KB
/
Controller.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
import java.util.Stack;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.lang.Runnable;
public class Controller
{
private Stack<ReversibleCommand> undoStack;
private Stack<ReversibleCommand> redoStack;
private TimeModel time;
private ArrayList<View> views;
public Controller()
{
undoStack = new Stack<ReversibleCommand>();
redoStack = new Stack<ReversibleCommand>();
views = new ArrayList<View>();
time = new TimeModel();
ScheduledExecutorService ticker = Executors.newScheduledThreadPool(1);
ticker.scheduleAtFixedRate(new Runnable()
{
@Override
public void run()
{
time.getTime().add(Calendar.SECOND, 1);
updateViews();
}
}, 0, 1, TimeUnit.SECONDS);
}
public TimeModel getModel()
{
return time;
}
public void setModel(TimeModel model)
{
time = model;
}
public void onReceiveCommand(Command command)
{
switch(command.getTargetClass().getName())
{
case "TimeModel":
{
command.assignTarget(time);
break;
}
case "Controller":
{
command.assignTarget(this);
break;
}
default:
{
throw new IllegalArgumentException("Unsupported class " + command.getTargetClass().getName());
}
}
command.execute();
if(command instanceof ReversibleCommand)
{
undoStack.push((ReversibleCommand)command);
redoStack.clear();
}
updateViews();
}
public void tryUndo()
{
if(!undoStack.empty())
{
ReversibleCommand command = undoStack.pop();
//Not all reversible commands will necessarily be undoable when we attempt to undo an action.
if(command.reverse()) redoStack.push(command);
}
}
public void tryRedo()
{
if(!redoStack.empty())
{
ReversibleCommand command = redoStack.pop();
command.execute();
undoStack.push(command);
}
}
public void addView(View view)
{
views.add(view);
}
public void removeView(View view)
{
views.remove(view);
}
public boolean findView(View view)
{
return views.contains(view);
}
public void updateViews()
{
Calendar now = time.getTime();
for(int i=0; i<views.size(); i++)
{
views.get(i).update(now);
}
}
}