Golang | 迭代器模式

  • 迭代器模式(Iterator Pattern)是一种行为型设计模式,它提供了一种顺序访问聚合对象(如列表、树等集合结构)中元素的方法,而无需暴露其底层实现细节。通过将遍历逻辑与集合本身解耦,迭代器模式使得集合可以更灵活地支持多种遍历方式。
  • 核心思想:
    • 解耦遍历逻辑:将遍历操作从集合类中分离出来,交给独立的迭代器对象处理。
    • 统一访问接口:为不同的集合结构(如数组、链表、树)提供一致的遍历接口。
  • 应用场景:
    • 需要遍历不同结构的集合(如数组、树、图)但希望客户端代码统一。
    • 需要支持多种遍历方式(如正序、逆序、过滤遍历)。
    • 隐藏集合的内部实现,提供安全的访问接口。
go 复制代码
package main

import "fmt"

// 迭代器接口
type Iterator interface {
	HasNext() bool
	Next() interface{}
}

// 集合接口
type Aggregate interface {
	Iterator() Iterator
}

// 具体集合(切片封装)
type ConcreteAggregate struct {
	items []interface{}
}

func NewConcreteAggregate(items []interface{}) *ConcreteAggregate {
	return &ConcreteAggregate{items: items}
}

// 创建迭代器
func (a *ConcreteAggregate) Iterator() Iterator {
	return &ConcreteIterator{
		aggregate: a,
		index:     0,
	}
}

// 具体迭代器
type ConcreteIterator struct {
	aggregate *ConcreteAggregate
	index     int
}

func (i *ConcreteIterator) HasNext() bool {
	return i.index < len(i.aggregate.items)
}

func (i *ConcreteIterator) Next() interface{} {
	if !i.HasNext() {
		return nil
	}
	val := i.aggregate.items[i.index]
	i.index++
	return val
}

func main() {
	// 使用示例
	agg := NewConcreteAggregate([]interface{}{"A", "B", 123, true})
	iterator := agg.Iterator()
	
	for iterator.HasNext() {
		fmt.Println(iterator.Next())
	}
}
go 复制代码
package main

import "fmt"

// 泛型迭代器接口
type Iterator[T any] interface {
	HasNext() bool
	Next() T
}

// 泛型集合接口
type Aggregate[T any] interface {
	Iterator() Iterator[T]
}

// 具体集合(泛型切片)
type SliceAggregate[T any] struct {
	items []T
}

func NewSliceAggregate[T any](items []T) *SliceAggregate[T] {
	return &SliceAggregate[T]{items: items}
}

func (a *SliceAggregate[T]) Iterator() Iterator[T] {
	return &SliceIterator[T]{
		slice: a.items,
		index: 0,
	}
}

// 具体迭代器(泛型)
type SliceIterator[T any] struct {
	slice []T
	index int
}

func (i *SliceIterator[T]) HasNext() bool {
	return i.index < len(i.slice)
}

func (i *SliceIterator[T]) Next() T {
	if !i.HasNext() {
		var zero T
		return zero
	}
	val := i.slice[i.index]
	i.index++
	return val
}

func main() {
	// 使用示例(字符串类型)
	strAgg := NewSliceAggregate([]string{"Hello", "Golang", "!"})
	strIter := strAgg.Iterator()
	for strIter.HasNext() {
		fmt.Println(strIter.Next())
	}

	// 使用示例(整数类型)
	intAgg := NewSliceAggregate([]int{1, 2, 3})
	intIter := intAgg.Iterator()
	for intIter.HasNext() {
		fmt.Println(intIter.Next())
	}
}
  • 迭代器模式要求集合类提供一个iterator方法,供别人遍历集合中的元素。
  • 迭代器模式不关心集合内部的数据结构,只要求通过next方法进行遍历。
  • 迭代器模式提高了代码的可读性和可维护性,使得遍历操作更加统一和规范





  • ConcurrentHashMap迭代器的核心成员变量包括要遍历的对象和内部存储的keys。
  • 通过二维数组或切片固定key的顺序,方便通过next方法遍历。
  • 构造函数初始化迭代器对象,包括设置要迭代的对象和keys。
  • next方法检查边界条件,通过递归处理空行情况,返回下一个key和value。
  • 迭代器模式提供了一种规范和要求,使得不同数据结构的遍历操作更加统一。
  • 通过接口定义行为规范,使得函数可以接受不同类型的迭代器参数。
  • 迭代器模式提高了代码的可读性和可维护性,使得遍历操作更加简洁和高效。
相关推荐
时见先生4 小时前
Python库和conda搭建虚拟环境
开发语言·人工智能·python·自然语言处理·conda
a努力。4 小时前
国家电网Java面试被问:混沌工程在分布式系统中的应用
java·开发语言·数据库·git·mysql·面试·职场和发展
Yvonne爱编码4 小时前
Java 四大内部类全解析:从设计本质到实战应用
java·开发语言·python
wqwqweee4 小时前
Flutter for OpenHarmony 看书管理记录App实战:搜索功能实现
开发语言·javascript·python·flutter·harmonyos
yongui478345 小时前
基于MATLAB的NALM锁模光纤激光器仿真实现
开发语言·matlab
-To be number.wan5 小时前
Python数据分析:numpy数值计算基础
开发语言·python·数据分析
Cx330❀6 小时前
【优选算法必刷100题】第038题(位运算):消失的两个数字
开发语言·c++·算法·leetcode·面试
Loo国昌6 小时前
深入理解 FastAPI:Python高性能API框架的完整指南
开发语言·人工智能·后端·python·langchain·fastapi
hoiii1877 小时前
16APSK/32APSK调制解调MATLAB仿真实现
开发语言·matlab·fpga开发
feifeigo1237 小时前
基于MATLAB的情感语音模板培训与识别实现方案
开发语言·matlab