-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcommand.cpp
More file actions
66 lines (55 loc) · 1.41 KB
/
command.cpp
File metadata and controls
66 lines (55 loc) · 1.41 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
#include <iostream>
#include <vector>
using namespace std;
struct BankAccount {
int balance{0};
int overdraft_limit{-500};
void deposit(int amount) {
balance += amount;
cout << "deposited " << amount << ", balance is now " << balance << "\n";
}
void withdraw(int amount) {
if (balance - amount >= overdraft_limit) {
balance -= amount;
cout << "withdrew " << amount << ", balance is now " << balance << "\n";
}
}
friend std::ostream &operator<<(std::ostream &os,
const BankAccount &account) {
os << "balance: " << account.balance;
return os;
}
};
struct Command {
virtual void call() = 0;
};
struct BankAccountCommand : Command {
BankAccount &account;
enum Action { deposit, withdraw } action;
int amount;
BankAccountCommand(BankAccount &account, Action action, int amount)
: account{account}, action{action}, amount{amount} {}
void call() override {
switch (action) {
case deposit:
account.deposit(amount);
break;
case withdraw:
account.withdraw(amount);
break;
}
}
};
int main() {
BankAccount ba;
vector<BankAccountCommand> commands{
BankAccountCommand{ba, BankAccountCommand::deposit, 100},
BankAccountCommand{ba, BankAccountCommand::withdraw, 200},
};
cout << ba << endl;
for (auto &cmd : commands) {
cmd.call();
}
cout << ba << endl;
return 0;
}