目录
????????迭代器模式(Iterator Pattern)提供了一种统一的方式来访问一个容器对象中的各个元素,而无需暴露其内部结构。
(1)优点:
(2)缺点:
package main
import "fmt"
// 音乐播放器,该播放器可以存储和管理多个音乐文件。希望能够遍历播放器中的所有音乐文件,并对其进行操作,例如播放、暂停、下一首等。
// 迭代器接口
type Iterator interface {
HasNext() bool
Next() interface{}
}
// 具体迭代器:音乐播放器迭代器
type MusicPlayerIterator struct {
musicPlayer *MusicPlayer
index int
}
func NewMusicPlayerIterator(musicPlayer *MusicPlayer) *MusicPlayerIterator {
return &MusicPlayerIterator{
musicPlayer: musicPlayer,
index: 0,
}
}
func (it *MusicPlayerIterator) HasNext() bool {
return it.index < len(it.musicPlayer.songs)
}
func (it *MusicPlayerIterator) Next() interface{} {
if it.HasNext() {
song := it.musicPlayer.songs[it.index]
it.index++
return song
}
return nil
}
// 容器:音乐播放器
type MusicPlayer struct {
songs []string
}
func (mp *MusicPlayer) AddSong(song string) {
mp.songs = append(mp.songs, song)
}
func (mp *MusicPlayer) GetIterator() Iterator {
return NewMusicPlayerIterator(mp)
}
// 客户端代码
func main() {
player := &MusicPlayer{}
player.AddSong("Song 1")
player.AddSong("Song 2")
player.AddSong("Song 3")
iterator := player.GetIterator()
for iterator.HasNext() {
song := iterator.Next().(string)
fmt.Println("Playing:", song)
}
}