81 lines
1.6 KiB
Go
81 lines
1.6 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
)
|
|
|
|
/*
|
|
实例:
|
|
汤宝宝聘请了一位私人助理,帮助他管理日常事务。
|
|
他负责记录汤宝宝的状态,以便在需要时恢复到之前的状态。
|
|
*/
|
|
|
|
// 原发器 - 汤宝宝
|
|
type Tom struct {
|
|
state string
|
|
}
|
|
|
|
func (t *Tom) CreateMemento() *Memento {
|
|
m := &Memento{}
|
|
m.setState(t.state)
|
|
fmt.Println("汤宝宝创建了备忘录,状态为:", t.state)
|
|
return m
|
|
}
|
|
|
|
func (t *Tom) RestoreMemento(memento *Memento) {
|
|
t.state = memento.GetState()
|
|
fmt.Println("汤宝宝恢复了状态:", t.state)
|
|
}
|
|
|
|
// 备忘录
|
|
type Memento struct {
|
|
state string
|
|
}
|
|
|
|
func (m *Memento) GetState() string {
|
|
return m.state
|
|
}
|
|
|
|
func (m *Memento) setState(state string) {
|
|
m.state = state
|
|
}
|
|
|
|
// 负责人 - 私人助理
|
|
type Assistant struct {
|
|
mementos []*Memento
|
|
}
|
|
|
|
func (a *Assistant) Backup(tom *Tom) {
|
|
a.mementos = append(a.mementos, tom.CreateMemento())
|
|
fmt.Println("私人助理备份了汤宝宝的状态")
|
|
}
|
|
|
|
func (a *Assistant) Undo(tom *Tom) {
|
|
if len(a.mementos) == 0 {
|
|
fmt.Println("没有备份可供恢复")
|
|
return
|
|
}
|
|
memento := a.mementos[len(a.mementos)-1]
|
|
a.mementos = a.mementos[:len(a.mementos)-1]
|
|
fmt.Println("私人助理恢复了汤宝宝的状态")
|
|
tom.RestoreMemento(memento)
|
|
}
|
|
|
|
func main() {
|
|
fmt.Println("============= 备忘录模式 =============")
|
|
|
|
tom := &Tom{state: "开心"}
|
|
fmt.Println("汤宝宝的当前状态:", tom.state)
|
|
assistant := &Assistant{}
|
|
|
|
assistant.Backup(tom)
|
|
|
|
tom.state = "生气"
|
|
fmt.Println("汤宝宝的当前状态:", tom.state)
|
|
|
|
assistant.Undo(tom)
|
|
|
|
fmt.Println()
|
|
fmt.Println("=========== 备忘录模式结束 ===========")
|
|
}
|