-
Notifications
You must be signed in to change notification settings - Fork 1
/
Command.java
121 lines (104 loc) · 2.73 KB
/
Command.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
116
117
118
119
120
121
// Command pattern
package behavioral.command;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class BankAccount
{
private int balance;
private int overdraftLimit = -500;
public void deposit(int amount)
{
balance += amount;
System.out.println("Deposited " + amount
+ ", balance is now " + balance);
}
public boolean withdraw(int amount)
{
if (balance - amount >= overdraftLimit)
{
balance -= amount;
System.out.println("Withdrew " + amount
+ ", balance is now " + balance);
return true;
}
else System.out.println("Cannot withdraw " + amount);
return false;
}
@Override
public String toString() {
return "BankAccount{" +
"balance=" + balance +
'}';
}
}
interface Command
{
void call(); // what you need to call to apply the command
void undo();
}
//Command design pattern here
class BankAccountCommand implements Command
{
private BankAccount account;
private boolean succeeded; //flag
@Override
public void call()
{
switch (action) {
case DEPOSIT:
succeeded = true;
account.deposit(amount);
break;
case WITHDRAW:
succeeded = account.withdraw(amount); // way to figure out if an operation succeeded
break;
}
}
@Override
public void undo()
{
if(!succeeded) return;
switch (action) {
case DEPOSIT:
account.withdraw(amount);
break;
case WITHDRAW:
account.deposit(amount);
break;
}
}
public enum Action
{
DEPOSIT, WITHDRAW // only two possible operations
}
private Action action;
private int amount;
public BankAccountCommand(BankAccount account, Action action, int amount) {
this.account = account;
this.action = action;
this.amount = amount;
}
}
class CommandDemo
{
public static void main(String[] args) {
BankAccount ba = new BankAccount();
System.out.println(ba);
List<BankAccountCommand> commands = new ArrayList<>(List.of(
new BankAccountCommand(ba, BankAccountCommand.Action.DEPOSIT, 100),
new BankAccountCommand(ba, BankAccountCommand.Action.WITHDRAW, 1000)
));
for (Command c : commands)
{
c.call();
System.out.println(ba);
}
Collections.reverse(commands);
for (Command c : commands)
{
c.undo();
System.out.println(ba);
}
}
}