这种订单、支付系统等设计应该考虑到的是线程安全问题,比如两个线程同时操作一个变量,要加锁,而且也要做到一方减少,另一方增加,二者同时发生同时结束,这个和mysql的一致性原则还有原子性很类似。但这道题是个单线程,只需要模拟即可。
type Bank struct {
balance []int64
}
func Constructor(balance []int64) Bank {
return Bank{
balance: balance,
}
}
func (this *Bank) Transfer(account1 int, account2 int, money int64) bool {
if account1 > len(this.balance) || account2 > len(this.balance) || this.balance[account1-1] < money {
return false
}
this.balance[account1-1] -= money
this.balance[account2-1] += money
return true
}
func (this *Bank) Deposit(account int, money int64) bool {
if account > len(this.balance) {
return false
}
this.balance[account-1] += money
return true
}
func (this *Bank) Withdraw(account int, money int64) bool {
if account > len(this.balance) || this.balance[account-1] < money {
return false
}
this.balance[account-1] -= money
return true
}
/**
* Your Bank object will be instantiated and called as such:
* obj := Constructor(balance);
* param_1 := obj.Transfer(account1,account2,money);
* param_2 := obj.Deposit(account,money);
* param_3 := obj.Withdraw(account,money);
*/