- 时间:2022-07-15 00:42 编辑: 来源: 阅读:297
- 扫一扫,手机访问
摘要:动手golang行为设计模式纪念品模式
<网站代码>
“golang行为设计模式”起源于memento模式,最近对设计模式进行了回顾。读谭永德的< & lt这就是你学习设计模式的方式>:& gt在这一系列音符中,golang所练习的Memento Pattern memento pattern,也被称为快照模式,或Token模式。它指的是捕获对象的内部状态,并在不破坏包的情况下将该状态保存在对象外部。 这样就可以将对象恢复到原来保存的状态,属于行为设计模式。 Memento模式主要适用于以下应用场景 (1)需要保存历史快照的场景 (2)希望状态保存在对象之外,其他类对象除了自己不能访问状态保存的具体内容。 (来自谭永德 爬到更高的地方,你可以欣赏到更壮丽的景色。 ”)编辑。Save() //测试show()编辑器。Show() //测试{ e := editor的undo()。Undo() if e!= nil { break } else { editor。Show() } } //为{ e := editor测试重做()。重做()if e!= nil { break } else { editor。show()} } } Output $ go test-v memento _ pattern _ test . go = = run test _ memento pattern mockeditor . show,title =唐诗在鹭宿王之欢,content=山遮白日,洋泄金河。 爬到更高的地方,你可以欣赏到更壮丽的景色。 TMockEditor。Show,title=唐诗在鹭楼,content=山遮白日,海泄金河。tMockEditor。Show,title=唐诗,content=山遮白日tMockEditor。Show,title=唐诗在鹭楼,content=山遮白日,海泄金河。tMockEditor。秀,title=唐诗在鹭楼王志焕,content=山遮白日,海泄金河 爬到更高的地方,你可以欣赏到更壮丽的景色。 -PASS:Test _ memento pattern(0.00s)PASS命令行-arguments 0.002sieditor.go定义编辑器接口包memo类型I编辑器接口{ title(title string)content(content string)Save()undo()errorredo()error show()} teditoremento . go定义编辑器的memo,即编辑器的内部状态数据模型,同时也对应一个版本历史包memento import“time”类型teditorumostruct { title string content string create time int 64 }。标题字符串,内容字符串)* tEditorMemento { return & ampTEDITORMENTO { title,content,time.now()。Unix(),}} tmockeditor.go虚拟编辑器类,实现IEditor接口包memento import(" errors " " fmt ")type tmockeditor struct { title string content string versions[]* tEditorMemento index int } func new mock editor()I editor { return & amp;tMockEditor{ ""," ",make([]*tEditorMemento,0),0,} } func(me * tMockEditor)Title(Title string){ me . Title = Title } func(me * tMockEditor)Content(Content string){ me . Content = Content } func(me * tMockEditor)Save(){ it:= neweditormememeto(me . Title,me . Content)me . versions = append(me . versions,it)me . index = len(me . versions)-1 } func= 0 {返回错误。New("无历史版本")}如果我& lt0 | | i & gt= size {返回错误。New("不再有历史版本")} it:= me . versions[I]me . title = it . title me . content = it . content me . index = I return nil } func(me * tMockEditor)Redo()error { return me . load(me . index+1)} func(me * tMockEditor)show(){ fmt . printf(" tMockEditor . show,title =% s,content =% s \ n ",me。标题,我。content)} memento模式总结了memento模式的优点(1)简化了发起者的责任,并且 (2)提供状态回滚功能。 memento模式和memento模式的缺点主要是资源消耗。 如果要保存的状态太多,每次保存都会消耗大量内存。 (来自谭永德