-
Notifications
You must be signed in to change notification settings - Fork 1
/
CommandCodingExercise.java
80 lines (68 loc) · 1.69 KB
/
CommandCodingExercise.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
/*
Exercise for Command patterns section
Implement Account.process() to process the different commands
*/
package behavioral.command;
class CommandImpl
{
enum Action
{
DEPOSIT, WITHDRAW
}
public Action action;
public int amount;
public boolean success;
public CommandImpl(Action action, int amount)
{
this.action = action;
this.amount = amount;
}
}
class Account
{
public int balance;
public Account() {}
public void process(CommandImpl c)
{
switch (c.action)
{
case DEPOSIT -> {
c.success = true;
balance += c.amount;
}
case WITHDRAW -> {
if (balance - c.amount < 0)
c.success = false;
else {
c.success = true;
balance -= c.amount;
}
}
}
}
@Override
public String toString() {
return "Account{" +
"balance=" + balance +
'}';
}
}
class CommandExercise
{
public static void main(String[] args)
{
Account a = new Account();
CommandImpl command = new CommandImpl(CommandImpl.Action.DEPOSIT, 100);
a.process(command);
System.out.println(a);
System.out.println(command.success);
command = new CommandImpl(CommandImpl.Action.WITHDRAW, 50);
a.process(command);
System.out.println(a);
System.out.println(command.success);
command = new CommandImpl(CommandImpl.Action.WITHDRAW, 150);
a.process(command);
System.out.println(a);
System.out.println(command.success);
}
}