forked from quanke/design-pattern-java-source-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCommand.java
More file actions
70 lines (59 loc) · 1.07 KB
/
Copy pathCommand.java
File metadata and controls
70 lines (59 loc) · 1.07 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
abstract class AbstractCommand
{
public abstract int execute(int value);
public abstract int undo();
}
class ConcreteCommand extends AbstractCommand
{
private Adder adder = new Adder();
private int value;
public int execute(int value)
{
this.value=value;
return adder.add(value);
}
public int undo()
{
return adder.add(-value);
}
}
class CalculatorForm
{
private AbstractCommand command;
public void setCommand(AbstractCommand command)
{
this.command=command;
}
public void compute(int value)
{
int i = command.execute(value);
System.out.println("执行运算,运算结果为:" + i);
}
public void undo()
{
int i = command.undo();
System.out.println("执行撤销,运算结果为:" + i);
}
}
class Adder
{
private int num=0;
public int add(int value)
{
num+=value;
return num;
}
}
class Client
{
public static void main(String args[])
{
CalculatorForm form = new CalculatorForm();
ConcreteCommand command = new ConcreteCommand();
form.setCommand(command);
form.compute(10);
form.compute(5);
form.compute(10);
form.undo();
}
}