golang设计模式(四)委托与反转控制
作者:互联网
/*
UndoIntSet是IntSet的功能扩展,可以进行undo操作
通过委托和反转控制将IntSet的逻辑和Undo的逻辑分开
undo的功能由委托给functions,这样可以实现IntSet依赖functions,
*/
type undo []func()
func (u *undo) Add(f func()) {
*u = append(*u,f)
}
func (u *undo) Undo() error{
functions := *u
if len(functions)==0{
return errors.New("do not undo")
}
index := len(functions)-1
if f := functions[index];f!=nil{
f()
functions[index]=nil
}
*u = functions[:index]
return nil
}
type UndoIntSet struct {
data map[int]bool
functions undo
}
func (s *UndoIntSet) Add(i int) {
if s.data[i]{
return
}
s.data[i]=true
s.functions = append(s.functions, func() {
delete(s.data,i)
})
}
func (s *UndoIntSet) remove(i int) {
if !s.data[i]{
return
}
delete(s.data,i)
s.functions = append(s.functions, func() {
s.data[i]=true
})
}
func (s *UndoIntSet) undo() {
s.functions.Undo()
}
标签:index,functions,反转,undo,golang,func,设计模式,data,UndoIntSet 来源: https://www.cnblogs.com/1token/p/15933409.html