특정한 시점으로 rollback 할 수 있음
class Memento
{
let balance : Int
init(_ balance: Int)
{
self.balance = balance
}
}
class BanckAccount: CustomStringConvertible
{
private var balance : Int
init(_ balance: Int)
{
self.balance = balance
}
func deposit(_ amount: Int) -> Memento
{
balance += amount
return Memento(balance)
}
func restore(_ m: Memento)
{
balance = m.balance
}
var description: String
{
return "Balance = \(balance)"
}
}
func main()
{
var ba = BanckAccount(400)
let m1 = ba.deposit(50) // 450
let m2 = ba.deposit(100) // 550
print(ba)
// restore to m1
ba.restore(m1)
print(ba)
// restore to m2
ba.restore(m2)
print(ba)
}
class BanckAccount: CustomStringConvertible
{
private var balance : Int
private var changes = [Memento]()
private var current = 0
init(_ balance: Int)
{
self.balance = balance
changes.append(Memento(balance))
}
func deposit(_ amount: Int) -> Memento
{
balance += amount
let m = Memento(balance)
changes.append(m)
current += 1
return m
}
func restore(_ m: Memento?)
{
if let mm = m
{
balance = mm.balance
changes.append(mm)
current = changes.count - 1
}
}
func undo() -> Memento?
{
if current > 0
{
current -= 1
let m = changes[current]
balance = m.balance
return m
}
return nil
}
func redo() -> Memento?
{
if (current+1) < changes.count
{
current += 1
let m = changes[current]
balance = m.balance
return m
}
return nil
}
var description: String
{
return "Balance = \(balance)"
}
}
func main()
{
var ba = BanckAccount(400)
let m1 = ba.deposit(50) // 450
let m2 = ba.deposit(100) // 550
print(ba)
ba.undo()
print("Undo 1 : \(ba)")
ba.undo()
print("Undo 2 : \(ba)")
ba.redo()
print("Redo 1 : \(ba)")
}