Iterator Pattern
The iterator pattern allows the object to be accessed in a way that can be encapsulated, only to implement its own iterator to a data structure, and the user can easily manipulate the data structure without needing to care about the underlying implementation simply by getting an iterator. Implement
Encapsulating a container
Package iterator
Import "container/list"
type container interface{
iterator () iterator
}
type List struct{List List
. List
}
func (this *list) Iterator () iterator{
return &listiterator{this.list.front (), This.list.Back ()}
}
func (this *list) Add (value interface{}) {
this.list.PushBack (value)
}
Implementing iterators for containers
Package iterator
Import (
"Container/list"
)
type iterator interface{
hasnext () bool
Value ( ) interface{}
Next ()
}
type listiterator struct {
cur *list. Element
End *list. Element
}
func (this *listiterator) hasnext () bool{
return this.cur! = This.end
}
func (this * Listiterator) Next () {
this.cur=this.cur.next ()
}
func (this *listiterator) Value () interface{}{
return This.cur.Value
}
Main.go
Package main
Import (
"Projects/designpatternsbygo/behavioralpatterns/iterator"
"FMT"
)
Func Main () {
L: = iterator. list{}
L.add (1)
L.add (2)
L.add (3)
L.add (4)
I: = L.iterator () for
I.hasnext () {
x: = I.value (). (int)
Fmt. PRINTLN (x)
i.next ()
}
}
Money to hold a court, no money in the holding of personal field.
It's not easy to come out.