-
Notifications
You must be signed in to change notification settings - Fork 10
/
UndoCommand.java
107 lines (73 loc) · 1.94 KB
/
UndoCommand.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
package com.camnter.basicexercises.design.command;
/**
* 撤销命令
*
* @author CaMnter
*/
class UndoCommand {
public static void main(String[] args) {
Calculator calculator = new Calculator();
AbstractCommand abstractCommand = new Command();
calculator.setCommand(abstractCommand);
calculator.compute(10);
calculator.compute(10);
calculator.compute(10);
calculator.undo();
}
/**
* 加法
*/
public static class Adder {
private int num;
public int add(int value) {
this.num += value;
return this.num;
}
}
/**
* 抽象命令类
*/
public static abstract class AbstractCommand {
public abstract int execute(int value);
/**
* 撤销
*
* @return int
*/
public abstract int undo();
}
/**
* 具体命令类
*/
public static class Command extends AbstractCommand {
private Adder adder = new Adder();
// 记录上一次操作的值
private int value;
@Override
public int execute(int value) {
this.value = value;
return this.adder.add(this.value);
}
@Override
public int undo() {
return this.adder.add(-this.value);
}
}
/**
* 计算器
*/
public static class Calculator {
private AbstractCommand command;
public void setCommand(AbstractCommand command) {
this.command = command;
}
public void compute(int value) {
final int result = this.command.execute(value);
System.out.println("[Calculator] [compute] [result] = " + result);
}
public void undo() {
final int result = this.command.undo();
System.out.println("[Calculator] [undo] [result] = " + result);
}
}
}