-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathContents.swift
90 lines (67 loc) · 1.86 KB
/
Contents.swift
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
protocol Command {
func execute()
var isComplete: Bool { get set}
}
class Account {
var accountName: String
var balance: Int
init(accountName: String, balance: Int) {
self.accountName = accountName
self.balance = balance
}
}
class Deposit: Command {
private var account: Account
private var amount: Int
var isComplete = false
init(account: Account, amount: Int) {
self.account = account
self.amount = amount
}
func execute() {
account.balance += amount
isComplete = true
}
}
class Withdraw: Command {
private var account: Account
private var amount: Int
var isComplete = false
init(account: Account, amount: Int) {
self.account = account
self.amount = amount
}
func execute() {
if account.balance >= amount {
account.balance -= amount
isComplete = true
} else {
print("Not enough money")
}
}
}
class TransactionManager {
static let shared = TransactionManager()
private init() {}
private var transaction: [Command] = []
var pendingTransactions: [Command] {
get {
self.transaction.filter{$0.isComplete == false }
}
}
func addTransactions(command: Command) {
self.transaction.append(command)
}
func processingTransaction() {
transaction.filter{$0.isComplete == false}.forEach{ $0.execute() }
}
}
//MARK: - Tests
let account = Account(accountName: "Kirill", balance: 1000)
TransactionManager.shared.addTransactions(command: Deposit(account: account, amount: 200))
TransactionManager.shared.pendingTransactions
TransactionManager.shared.processingTransaction()
account.balance
TransactionManager.shared.addTransactions(command: Withdraw(account: account, amount: 800))
TransactionManager.shared.processingTransaction()
account.balance