Skip to content

Instantly share code, notes, and snippets.

@kien-hoang
Last active January 31, 2023 08:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kien-hoang/60e026d1f26342e22a9690373be9f2bc to your computer and use it in GitHub Desktop.
Save kien-hoang/60e026d1f26342e22a9690373be9f2bc to your computer and use it in GitHub Desktop.
Memento Pattern in Swift
/*
Memento Pattern
1. The `originator` is the object to be saved or restored.
2. The `memento` represents a stored state.
3. The `caretaker` requests a save from the originator and receives a memento in response.
The caretaker is responsible for persisting the memento and, later on,
providing the memento back to the originator to restore the originator’s state.
*/
protocol Originator {
func save() -> Memento
func restore(memento: Memento)
}
class BankAccount: Originator {
private(set) var balance: Double = 0.0
func setBalance(balance: Double) {
self.balance = balance
}
func save() -> Memento {
return Memento(balance: balance)
}
func restore(memento: Memento) {
balance = memento.balance
}
}
class Memento {
let balance: Double
init(balance: Double) {
self.balance = balance
}
}
// Care Taker
class BankCustomer {
let account: BankAccount
init(account: BankAccount) {
self.account = account
}
func withdraw(amount: Double) {
let memento = account.save()
account.setBalance(balance: account.balance - amount)
if account.balance < 0 {
account.restore(memento: memento)
print("Insufficient funds.")
}
}
func deposit(amount: Double) {
account.setBalance(balance: account.balance + amount)
}
}
let account = BankAccount()
let customer = BankCustomer(account: account)
print("Balance: \(customer.account.balance)")
print("\nDeposit 100")
customer.deposit(amount: 100)
print("Balance: \(customer.account.balance)")
print("\nWithdraw 50")
customer.withdraw(amount: 50)
print("Balance: \(customer.account.balance)")
print("\nWithdraw 100")
customer.withdraw(amount: 100)
print("Balance: \(customer.account.balance)")
/*
Balance: 0.0
Deposit 100
Balance: 100.0
Withdraw 50
Balance: 50.0
Withdraw 100
Insufficient funds.
Balance: 50.0
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment