/*
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()
}