Skip to content

Commit 1ee724c

Browse files
committed
Basic examples
1 parent 8fae036 commit 1ee724c

2 files changed

Lines changed: 108 additions & 0 deletions

File tree

JavaScript/1-active.js

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
'use strict';
2+
3+
class AccountCommand {
4+
constructor(account, amount) {
5+
this.account = account;
6+
this.amount = amount;
7+
}
8+
execute() {
9+
throw new Error('Command is not implemented');
10+
}
11+
}
12+
13+
class Withdraw extends AccountCommand {
14+
execute() {
15+
this.account.balance -= this.amount;
16+
}
17+
}
18+
19+
class Income extends AccountCommand {
20+
execute() {
21+
this.account.balance += this.amount;
22+
}
23+
}
24+
25+
class BankAccount { // Receiver or Target
26+
constructor(name) {
27+
this.name = name;
28+
this.balance = 0;
29+
}
30+
}
31+
32+
class Bank { // Invoker
33+
constructor() {
34+
this.commands = [];
35+
}
36+
operation(account, amount) {
37+
const Command = amount < 0 ? Withdraw : Income;
38+
const command = new Command(account, Math.abs(amount));
39+
command.execute();
40+
this.commands.push(command);
41+
}
42+
showOperations() {
43+
const output = [];
44+
for (const command of this.commands) {
45+
output.push({
46+
operation: command.constructor.name,
47+
account: command.account.name,
48+
amount: command.amount
49+
});
50+
}
51+
console.table(output);
52+
}
53+
}
54+
55+
// Usage
56+
57+
const bank = new Bank();
58+
const account1 = new BankAccount('Marcus Aurelius');
59+
bank.operation(account1, 1000);
60+
bank.operation(account1, -50);
61+
const account2 = new BankAccount('Antoninus Pius');
62+
bank.operation(account2, 500);
63+
bank.operation(account2, 150);
64+
bank.showOperations();

JavaScript/2-anemic.js

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
'use strict';
2+
3+
class AccountCommand {
4+
constructor(operation, account, amount) {
5+
this.operation = operation;
6+
this.account = account;
7+
this.amount = amount;
8+
}
9+
}
10+
11+
class BankAccount {
12+
constructor(name) {
13+
this.name = name;
14+
this.balance = 0;
15+
}
16+
}
17+
18+
class Bank {
19+
constructor() {
20+
this.commands = [];
21+
}
22+
operation(account, amount) {
23+
const operation = amount < 0 ? 'Withdraw' : 'Income';
24+
const command = new AccountCommand(
25+
operation, account.name, Math.abs(amount)
26+
);
27+
this.commands.push(command);
28+
account.balabce += amount;
29+
}
30+
showOperations() {
31+
console.table(this.commands);
32+
}
33+
}
34+
35+
// Usage
36+
37+
const bank = new Bank();
38+
const account1 = new BankAccount('Marcus Aurelius');
39+
bank.operation(account1, 1000);
40+
bank.operation(account1, -50);
41+
const account2 = new BankAccount('Antoninus Pius');
42+
bank.operation(account2, 500);
43+
bank.operation(account2, 150);
44+
bank.showOperations();

0 commit comments

Comments
 (0)