-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathcomposite_command.py
More file actions
150 lines (118 loc) · 4.19 KB
/
composite_command.py
File metadata and controls
150 lines (118 loc) · 4.19 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
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
# Composite Command a.k.a. Macro
# also: Composite design pattern ;)
import unittest
from abc import ABC, abstractmethod
from enum import Enum
class BankAccount:
OVERDRAFT_LIMIT = -500
def __init__(self, balance=0):
self.balance = balance
def deposit(self, amount):
self.balance += amount
print(f'Deposited {amount}, balance = {self.balance}')
def withdraw(self, amount):
if self.balance - amount >= BankAccount.OVERDRAFT_LIMIT:
self.balance -= amount
print(f'Withdrew {amount}, balance = {self.balance}')
return True
return False
def __str__(self):
return f'Balance = {self.balance}'
class Command(ABC):
def __init__(self):
self.success = False
def invoke(self):
pass
def undo(self):
pass
class BankAccountCommand(Command):
def __init__(self, account, action, amount):
super().__init__()
self.amount = amount
self.action = action
self.account = account
class Action(Enum):
DEPOSIT = 0
WITHDRAW = 1
def invoke(self):
if self.action == self.Action.DEPOSIT:
self.account.deposit(self.amount)
self.success = True
elif self.action == self.Action.WITHDRAW:
self.success = self.account.withdraw(self.amount)
def undo(self):
if not self.success:
return
# strictly speaking this is not correct
# (you don't undo a deposit by withdrawing)
# but it works for this demo, so...
if self.action == self.Action.DEPOSIT:
self.account.withdraw(self.amount)
elif self.action == self.Action.WITHDRAW:
self.account.deposit(self.amount)
# try using this before using MoneyTransferCommand!
class CompositeBankAccountCommand(Command, list):
def __init__(self, items=[]):
super().__init__()
for i in items:
self.append(i)
def invoke(self):
for x in self:
x.invoke()
def undo(self):
for x in reversed(self):
x.undo()
class MoneyTransferCommand(CompositeBankAccountCommand):
def __init__(self, from_acct, to_acct, amount):
super().__init__([
BankAccountCommand(from_acct,
BankAccountCommand.Action.WITHDRAW,
amount),
BankAccountCommand(to_acct,
BankAccountCommand.Action.DEPOSIT,
amount)])
def invoke(self):
ok = True
for cmd in self:
if ok:
cmd.invoke()
ok = cmd.success
else:
cmd.success = False
self.success = ok
class TestSuite(unittest.TestCase):
def test_composite_deposit(self):
BA = BankAccount()
deposit1 = BankAccountCommand(BA,
BankAccountCommand.Action.DEPOSIT, 1000)
deposit2 = BankAccountCommand(BA,
BankAccountCommand.Action.DEPOSIT, 1000)
composite = CompositeBankAccountCommand([deposit1, deposit2])
composite.invoke()
print(BA)
composite.undo()
print(BA)
def test_transfer_fail(self):
ba1 = BankAccount(100)
ba2 = BankAccount()
# composite isn't so good because of failure
amount = 1000 # try 1000: no transactions should happen
wc = BankAccountCommand(ba1,
BankAccountCommand.Action.WITHDRAW, amount)
dc = BankAccountCommand(ba2,
BankAccountCommand.Action.DEPOSIT, amount)
transfer = CompositeBankAccountCommand([wc, dc])
transfer.invoke()
print('ba1:', ba1, 'ba2:', ba2) # end up in incorrect state
transfer.undo()
print('ba1:', ba1, 'ba2:', ba2)
def test_better_tranfer(self):
ba1 = BankAccount(100)
ba2 = BankAccount()
amount = 1000
transfer = MoneyTransferCommand(ba1, ba2, amount)
transfer.invoke()
print('ba1:', ba1, 'ba2:', ba2)
transfer.undo()
print('ba1:', ba1, 'ba2:', ba2)
print(transfer.success)