【发布时间】:2021-09-19 13:57:03
【问题描述】:
我正在关注“Swift 5 中的设计模式”一书中的示例代码。该示例适用于状态模式部分。
我收到内存访问错误:“同时访问 0x14572f2a0,但修改需要独占访问。”当我尝试运行代码时。
我不确定发生了什么...提前致谢!
代码:
import Foundation
public final class ATM {
fileprivate var state: ATMState = IdleState()
public func enter(pin: String) {
state = EnterPinState(context: self)
state.validate(pin: pin)
}
public func withdraw(amount: Float) -> Bool {
return state.withdraw(amount: amount)
}
}
fileprivate protocol ATMState {
func validate(pin: String)
mutating func withdraw(amount: Float) -> Bool
func transactionCompleted(success:Bool)
}
extension ATMState {
func validate(pin:String) {
print("not implemented")
}
mutating func withdraw(amount: Float) -> Bool {
print("not implemented")
return false
}
func transactionCompleted(success:Bool) {
print("not implemented")
}
}
fileprivate struct IdleState: ATMState {
}
fileprivate struct EnterPinState: ATMState {
let context: ATM
func validate(pin: String) {
guard pin == "1234" else {
print("wrong pin")
context.state = TransactionCompleteState(context:context)
context.state.transactionCompleted(success: false)
return
}
print("pin ok")
context.state = WithdrawState(context: context)
}
}
fileprivate struct TransactionCompleteState: ATMState {
let context: ATM
func transactionCompleted(success: Bool) {
var statusMessage = success ? "Transaction complete..." : "Transaction failed..."
print(statusMessage)
context.state = IdleState()
}
}
fileprivate struct WithdrawState: ATMState {
var context: ATM
var availableFunds: Float = 1000
init(context: ATM) {
self.context = context
}
mutating func withdraw(amount: Float) -> Bool {
print("Withdraw $\(amount)")
guard amount > 0 && availableFunds >= amount else {
print("invalid")
context.state = TransactionCompleteState(context: context)
context.state.transactionCompleted(success: false)
return false
}
availableFunds -= amount
context.state = TransactionCompleteState(context: context)
context.state.transactionCompleted(success: true)
return true
}
}
let atm = ATM()
atm.enter(pin:"1234")
atm.withdraw(amount: 10)
【问题讨论】:
标签: swift