惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

人人都是产品经理
人人都是产品经理
MyScale Blog
MyScale Blog
Y
Y Combinator Blog
罗磊的独立博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
P
Proofpoint News Feed
Google DeepMind News
Google DeepMind News
V
Vulnerabilities – Threatpost
T
The Blog of Author Tim Ferriss
云风的 BLOG
云风的 BLOG
Recorded Future
Recorded Future
N
News and Events Feed by Topic
B
Blog RSS Feed
阮一峰的网络日志
阮一峰的网络日志
博客园_首页
C
CXSECURITY Database RSS Feed - CXSecurity.com
博客园 - 【当耐特】
N
Netflix TechBlog - Medium
博客园 - 叶小钗
B
Blog
Vercel News
Vercel News
T
Tenable Blog
T
The Exploit Database - CXSecurity.com
Spread Privacy
Spread Privacy
T
Threat Research - Cisco Blogs
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Last Week in AI
Last Week in AI
F
Fortinet All Blogs
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Microsoft Security Blog
Microsoft Security Blog
S
Securelist
Microsoft Azure Blog
Microsoft Azure Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
P
Palo Alto Networks Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
D
DataBreaches.Net
Cyberwarzone
Cyberwarzone
Engineering at Meta
Engineering at Meta
Martin Fowler
Martin Fowler
G
GRAHAM CLULEY
Project Zero
Project Zero
Cisco Talos Blog
Cisco Talos Blog
A
Arctic Wolf
C
CERT Recently Published Vulnerability Notes
L
LangChain Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
C
Check Point Blog
A
About on SuperTechFans
W
WeLiveSecurity
The GitHub Blog
The GitHub Blog

博客园 - ®Geovin Du Dream Park™

go: Functional Options Pattern go:Timing Functions Pattern python: Timing Functions Pattern go: Steady-State Pattern python: Steady-State Pattern go: Handshaking Pattern python: Handshaking Pattern go: Fail-Fast Pattern python: Fail-Fast Pattern I go: Deadline Pattern python: Deadline Pattern go: Circuit-Breaker Pattern python: Circuit-Breaker Pattern go: Bulkheads Pattern python: Bulkheads Pattern go: Push & Pull Pattern python: Push & Pull Pattern python: Publish/Subscribe Pattern II go: Publish/Subscribe Pattern python: Publish/Subscribe Pattern go: Futures & Promises Pattern python: Futures & Promises Pattern go: Worker Pool Pattern go:Pipeline Pattern python: Worker Pool Pattern python: Pipeline Pattern go: Fan-Out Pattern python: Fan-Out Pattern go: Fan-In Pattern python: Fan-In Pattern Fan-In go: Producer Consumer  Pattern python: Producer Consumer Pattern go: Parallelism Pattern python: Parallelism Pattern go: Reactor Pattern python: Reactor Pattern go: Generators Pattern python: speech to text offline python: Generators Pattern go: Coroutines Pattern python:Coroutines Pattern go: Broadcast Pattern python: Broadcast Pattern python: Bounded Parallelism Pattern go: Bounded Parallelism Pattern python: N-Barrier Pattern go: N-Barrier Pattern python: Semaphore Pattern go: Semaphore Pattern python: Read-Write Lock Pattern go: Read-Write Lock Pattern python: Monitor Pattern go: Monitor Pattern python: Mutex Pattern go: Lock/Mutex Pattern Python: Condition Variable Pattern go:Condition Variable Pattern python: Registry Pattern python: Interpreter Pattern go: Interpreter Pattern go: Registry Pattern go: Memento Pattern go: Command Pattern go: State Pattern go:Template Method Pattern go: Strategy Pattern go: Visitor Pattern go: Observer Pattern go: Mediator Pattern go: Chain of Responsibility Pattern go: Proxy Pattern go:Decorator Pattern go: Facade Pattern go: Flyweight Pattern go: Composite Pattern go: Singleton Pattern go: Prototype Pattern go: Bridge Pattern go: Adapter Pattern go: Builder Pattern 密码进行加盐哈希 using CSharp,Python,Go,Java go: Abstract Factory Pattern go: Model,Interface,DAL ,Factory,BLL using mysql go: Simple Factory Pattern go: Factory Method Pattern go: goLang 在Windows环境搭建Go语言开发环境 CSharp: Parallel Extensions cpp: class python: 蝴蝶跟随鼠标 javascript: 中国历史人物热力分布图using echart javascript: 中国历史人物热力图 python: 初养龙虾微信纯文字自动回复using workBuddy python: object 入门 python: Factory Method Pattern python: Simple Factory Pattern python: Abstract Factory Pattern 区域化 代码 python: Null Object Pattern python: Builder Pattern python: Adapter Pattern
go: Iterator Pattern
®Geovin Du D · 2026-04-21 · via 博客园 - ®Geovin Du Dream Park™

项目结构:

image

/*
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述: Iterator Pattern 迭代器模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : goLang 2024.3.6 go 26.2
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/4/21 21:50
# User      :  geovindu
# Product   : GoLand
# Project   : godesginpattern
# File      : jewelry.go
*/
package domain

// Jewelry 珠宝领域模型(唯一职责:描述珠宝属性)
type Jewelry struct {
	ID       uint64  `json:"id"`
	Name     string  `json:"name"`
	Material string  `json:"material"`
	Price    float64 `json:"price"`
	Brand    string  `json:"brand"`
}
/*
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述: Iterator Pattern 迭代器模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : goLang 2024.3.6 go 26.2
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/4/21 21:51
# User      :  geovindu
# Product   : GoLand
# Project   : godesginpattern
# File      : collection.go
*/
package collection

import "godesginpattern/iterator/domain"

// JewelryCollection 珠宝集合接口
type JewelryCollection interface {
	Add(jewelry *domain.Jewelry)
	GetJewelryList() []*domain.Jewelry
}


/*
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述: Iterator Pattern 迭代器模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : goLang 2024.3.6 go 26.2
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/4/21 21:51
# User      :  geovindu
# Product   : GoLand
# Project   : godesginpattern
# File      : jewelry_box.go
*/
package collection

import "godesginpattern/iterator/domain"

// JewelryBox 珠宝盒(唯一职责:存储、管理珠宝列表)
type JewelryBox struct {
	jewelries []*domain.Jewelry
}

func NewJewelryBox() *JewelryBox {
	return &JewelryBox{
		jewelries: make([]*domain.Jewelry, 0),
	}
}

// Add 添加珠宝
func (j *JewelryBox) Add(jewelry *domain.Jewelry) {
	j.jewelries = append(j.jewelries, jewelry)
}

// GetJewelryList 对外提供安全访问(禁止外部直接修改切片)
func (j *JewelryBox) GetJewelryList() []*domain.Jewelry {
	return j.jewelries
}
/*
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Iterator Pattern 迭代器模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : goLang 2024.3.6 go 26.2
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/4/21 22:01
# User      :  geovindu
# Product   : GoLand
# Project   : godesginpattern
# File      : brand_iterator.go
*/
package iterator

import (
	"godesginpattern/iterator/collection"
	"godesginpattern/iterator/domain"
	"strings"
)

// BrandIterator 品牌过滤迭代器
type BrandIterator struct {
	box      *collection.JewelryBox
	index    int
	brand    string
	filtered []*domain.Jewelry
}

func NewBrandIterator(box *collection.JewelryBox, brand string) *BrandIterator {
	bi := &BrandIterator{
		box:   box,
		brand: strings.TrimSpace(brand),
	}
	bi.doFilter()
	return bi
}

func (b *BrandIterator) doFilter() {
	b.filtered = make([]*domain.Jewelry, 0)
	for _, j := range b.box.GetJewelryList() {
		if strings.EqualFold(j.Brand, b.brand) {
			b.filtered = append(b.filtered, j)
		}
	}
}

func (b *BrandIterator) HasNext() bool {
	return b.index < len(b.filtered)
}

func (b *BrandIterator) Next() *domain.Jewelry {
	if !b.HasNext() {
		return nil
	}
	item := b.filtered[b.index]
	b.index++
	return item
}

func (b *BrandIterator) Reset() {
	b.index = 0
}



/*
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Iterator Pattern 迭代器模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : goLang 2024.3.6 go 26.2
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/4/21 22:06
# User      :  geovindu
# Product   : GoLand
# Project   : godesginpattern
# File      : composite_iterator.go
*/
package iterator

import (
	"godesginpattern/iterator/collection"
	"godesginpattern/iterator/domain"
)

// CompositeFilter 组合过滤条件
type CompositeFilter struct {
	MinPrice float64
	MaxPrice float64
	Brand    string
	Material string
}

type CompositeIterator struct {
	box      *collection.JewelryBox
	index    int
	filter   CompositeFilter
	filtered []*domain.Jewelry
}

func NewCompositeIterator(box *collection.JewelryBox, filter CompositeFilter) *CompositeIterator {
	ci := &CompositeIterator{
		box:    box,
		filter: filter,
	}
	ci.doFilter()
	return ci
}

func (c *CompositeIterator) doFilter() {
	c.filtered = make([]*domain.Jewelry, 0)
	for _, j := range c.box.GetJewelryList() {
		// 价格
		if c.filter.MinPrice > 0 && j.Price < c.filter.MinPrice {
			continue
		}
		if c.filter.MaxPrice > 0 && j.Price > c.filter.MaxPrice {
			continue
		}
		// 品牌
		if c.filter.Brand != "" && j.Brand != c.filter.Brand {
			continue
		}
		// 材质
		if c.filter.Material != "" && j.Material != c.filter.Material {
			continue
		}
		c.filtered = append(c.filtered, j)
	}
}

func (c *CompositeIterator) HasNext() bool {
	return c.index < len(c.filtered)
}

func (c *CompositeIterator) Next() *domain.Jewelry {
	if !c.HasNext() {
		return nil
	}
	item := c.filtered[c.index]
	c.index++
	return item
}

func (c *CompositeIterator) Reset() {
	c.index = 0
}


/*
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Iterator Pattern 迭代器模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : goLang 2024.3.6 go 26.2
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/4/21 22:07
# User      :  geovindu
# Product   : GoLand
# Project   : godesginpattern
# File      : concurrent_iterator.go
*/
package iterator

import (
	"godesginpattern/iterator/collection"
	"godesginpattern/iterator/domain"
	"sync"
)

// ConcurrentIterator 并发安全迭代器
type ConcurrentIterator struct {
	box   *collection.JewelryBox
	index int
	mu    sync.RWMutex // 读写锁,保证并发安全
}

func NewConcurrentIterator(box *collection.JewelryBox) *ConcurrentIterator {
	return &ConcurrentIterator{
		box:   box,
		index: 0,
	}
}

func (ci *ConcurrentIterator) HasNext() bool {
	ci.mu.RLock()
	defer ci.mu.RUnlock()
	return ci.index < len(ci.box.GetJewelryList())
}

func (ci *ConcurrentIterator) Next() *domain.Jewelry {
	ci.mu.Lock()
	defer ci.mu.Unlock()

	if ci.index >= len(ci.box.GetJewelryList()) {
		return nil
	}
	item := ci.box.GetJewelryList()[ci.index]
	ci.index++
	return item
}

func (ci *ConcurrentIterator) Reset() {
	ci.mu.Lock()
	defer ci.mu.Unlock()
	ci.index = 0
}


/*
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述: Iterator Pattern 迭代器模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : goLang 2024.3.6 go 26.2
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/4/21 21:50
# User      :  geovindu
# Product   : GoLand
# Project   : godesginpattern
# File      : iterator.go
*/
package iterator

import "godesginpattern/iterator/domain"

// Iterator 迭代器顶层接口(企业级标准)
type Iterator interface {
	HasNext() bool
	Next() *domain.Jewelry
	Reset() // 扩展:重置迭代器
}

// IterableCollection 约束集合必须能创建迭代器
// 放在这里:接口依赖收敛,降低循环依赖
type IterableCollection interface {
	CreateIterator() Iterator
	CreateReverseIterator() Iterator
}


/*
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述: Iterator Pattern 迭代器模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : goLang 2024.3.6 go 26.2
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/4/21 21:51
# User      :  geovindu
# Product   : GoLand
# Project   : godesginpattern
# File      : jewelry_iterator.go
*/
package iterator

import (
	"godesginpattern/iterator/collection"
	"godesginpattern/iterator/domain"
)

// JewelryIterator 正向迭代器(单一职责:正向遍历)
type JewelryIterator struct {
	box   *collection.JewelryBox
	index int
}

func NewJewelryIterator(box *collection.JewelryBox) *JewelryIterator {
	return &JewelryIterator{
		box:   box,
		index: 0,
	}
}

func (j *JewelryIterator) HasNext() bool {
	return j.index < len(j.box.GetJewelryList())
}

func (j *JewelryIterator) Next() *domain.Jewelry {
	if !j.HasNext() {
		return nil
	}
	item := j.box.GetJewelryList()[j.index]
	j.index++
	return item
}

// Reset 重置迭代器(企业级必须具备的可复用能力)
func (j *JewelryIterator) Reset() {
	j.index = 0
}


/*
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Iterator Pattern 迭代器模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : goLang 2024.3.6 go 26.2
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/4/21 22:06
# User      :  geovindu
# Product   : GoLand
# Project   : godesginpattern
# File      : material_iterator.go
*/
package iterator

import (
	"godesginpattern/iterator/collection"
	"godesginpattern/iterator/domain"
	"strings"
)

type MaterialIterator struct {
	box      *collection.JewelryBox
	index    int
	material string
	filtered []*domain.Jewelry
}

func NewMaterialIterator(box *collection.JewelryBox, material string) *MaterialIterator {
	mi := &MaterialIterator{
		box:      box,
		material: strings.TrimSpace(material),
	}
	mi.doFilter()
	return mi
}

func (m *MaterialIterator) doFilter() {
	m.filtered = make([]*domain.Jewelry, 0)
	for _, j := range m.box.GetJewelryList() {
		if strings.Contains(strings.ToLower(j.Material), strings.ToLower(m.material)) {
			m.filtered = append(m.filtered, j)
		}
	}
}

func (m *MaterialIterator) HasNext() bool {
	return m.index < len(m.filtered)
}

func (m *MaterialIterator) Next() *domain.Jewelry {
	if !m.HasNext() {
		return nil
	}
	item := m.filtered[m.index]
	m.index++
	return item
}

func (m *MaterialIterator) Reset() {
	m.index = 0
}


/*
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Iterator Pattern 迭代器模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : goLang 2024.3.6 go 26.2
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/4/21 22:01
# User      :  geovindu
# Product   : GoLand
# Project   : godesginpattern
# File      : page_iterator.go
*/
package iterator

import (
	"godesginpattern/iterator/collection"
	"godesginpattern/iterator/domain"
)

// PageIterator 分页迭代器
type PageIterator struct {
	box    *collection.JewelryBox
	offset int // 起始索引
	limit  int // 每页数量
	index  int
	total  int
}

// NewPageIterator pageNum:页码  pageSize:每页条数
func NewPageIterator(box *collection.JewelryBox, pageNum, pageSize int) *PageIterator {
	if pageNum < 1 {
		pageNum = 1
	}
	if pageSize < 1 {
		pageSize = 10
	}

	total := len(box.GetJewelryList())
	offset := (pageNum - 1) * pageSize

	return &PageIterator{
		box:    box,
		offset: offset,
		limit:  pageSize,
		index:  0,
		total:  total,
	}
}

func (p *PageIterator) HasNext() bool {
	currIdx := p.offset + p.index
	return currIdx < p.total && p.index < p.limit
}

func (p *PageIterator) Next() *domain.Jewelry {
	if !p.HasNext() {
		return nil
	}
	currIdx := p.offset + p.index
	item := p.box.GetJewelryList()[currIdx]
	p.index++
	return item
}

func (p *PageIterator) Reset() {
	p.index = 0
}


/*
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Iterator Pattern 迭代器模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : goLang 2024.3.6 go 26.2
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/4/21 22:00
# User      :  geovindu
# Product   : GoLand
# Project   : godesginpattern
# File      : price_iterator.go
*/
package iterator

import (
	"godesginpattern/iterator/collection"
	"godesginpattern/iterator/domain"
)

// PriceIterator 价格区间筛选迭代器
type PriceIterator struct {
	box      *collection.JewelryBox
	index    int
	minPrice float64
	maxPrice float64
	filtered []*domain.Jewelry // 预过滤缓存
}

// NewPriceIterator 创建价格筛选迭代器
func NewPriceIterator(box *collection.JewelryBox, min, max float64) *PriceIterator {
	pi := &PriceIterator{
		box:      box,
		minPrice: min,
		maxPrice: max,
	}
	pi.doFilter() // 预过滤
	return pi
}

// 内部:价格过滤
func (p *PriceIterator) doFilter() {
	p.filtered = make([]*domain.Jewelry, 0)
	for _, j := range p.box.GetJewelryList() {
		if j.Price >= p.minPrice && j.Price <= p.maxPrice {
			p.filtered = append(p.filtered, j)
		}
	}
}

func (p *PriceIterator) HasNext() bool {
	return p.index < len(p.filtered)
}

func (p *PriceIterator) Next() *domain.Jewelry {
	if !p.HasNext() {
		return nil
	}
	item := p.filtered[p.index]
	p.index++
	return item
}

func (p *PriceIterator) Reset() {
	p.index = 0
}


/*
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述: Iterator Pattern 迭代器模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : goLang 2024.3.6 go 26.2
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/4/21 21:51
# User      :  geovindu
# Product   : GoLand
# Project   : godesginpattern
# File      : reverse_iterator.go
*/
package iterator

import (
	"godesginpattern/iterator/collection"
	"godesginpattern/iterator/domain"
)

// ReverseJewelryIterator 反向迭代器(开闭原则体现)
type ReverseJewelryIterator struct {
	box   *collection.JewelryBox
	index int
}

func NewReverseJewelryIterator(box *collection.JewelryBox) *ReverseJewelryIterator {
	return &ReverseJewelryIterator{
		box:   box,
		index: len(box.GetJewelryList()) - 1,
	}
}

func (r *ReverseJewelryIterator) HasNext() bool {
	return r.index >= 0
}

func (r *ReverseJewelryIterator) Next() *domain.Jewelry {
	if !r.HasNext() {
		return nil
	}
	item := r.box.GetJewelryList()[r.index]
	r.index--
	return item
}

func (r *ReverseJewelryIterator) Reset() {
	r.index = len(r.box.GetJewelryList()) - 1
}


/*
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Iterator Pattern 迭代器模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : goLang 2024.3.6 go 26.2
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/4/21 22:06
# User      :  geovindu
# Product   : GoLand
# Project   : godesginpattern
# File      : sort_iterator.go
*/
package iterator

import (
	"godesginpattern/iterator/collection"
	"godesginpattern/iterator/domain"
	"sort"
)

const (
	SortAsc  = iota // 升序
	SortDesc        // 降序
)

type SortIterator struct {
	box      *collection.JewelryBox
	index    int
	sortType int
	sorted   []*domain.Jewelry
}

func NewSortIterator(box *collection.JewelryBox, sortType int) *SortIterator {
	si := &SortIterator{
		box:      box,
		sortType: sortType,
	}
	si.doSort()
	return si
}

func (s *SortIterator) doSort() {
	list := s.box.GetJewelryList()
	s.sorted = make([]*domain.Jewelry, len(list))
	copy(s.sorted, list)

	if s.sortType == SortAsc {
		sort.Slice(s.sorted, func(i, j int) bool {
			return s.sorted[i].Price < s.sorted[j].Price
		})
	} else {
		sort.Slice(s.sorted, func(i, j int) bool {
			return s.sorted[i].Price > s.sorted[j].Price
		})
	}
}

func (s *SortIterator) HasNext() bool {
	return s.index < len(s.sorted)
}

func (s *SortIterator) Next() *domain.Jewelry {
	if !s.HasNext() {
		return nil
	}
	item := s.sorted[s.index]
	s.index++
	return item
}

func (s *SortIterator) Reset() {
	s.index = 0
}
/*
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述: Iterator Pattern 迭代器模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : goLang 2024.3.6 go 26.2
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/4/21 21:51
# User      :  geovindu
# Product   : GoLand
# Project   : godesginpattern
# File      : jewelry_service.go
*/
package service

import (
	"godesginpattern/iterator/collection"
	"godesginpattern/iterator/domain"
	"godesginpattern/iterator/iterator"
)

// JewelryService 珠宝业务服务(上层唯一调用入口)
type JewelryService struct {
	jewelryBox *collection.JewelryBox
}

func NewJewelryService() *JewelryService {
	return &JewelryService{
		jewelryBox: collection.NewJewelryBox(),
	}
}

// AddJewelry 业务方法:添加珠宝
func (s *JewelryService) AddJewelry(j *domain.Jewelry) {
	s.jewelryBox.Add(j)
}

// ListForward 业务方法:正向遍历珠宝
func (s *JewelryService) ListForward() []*domain.Jewelry {
	iter := iterator.NewJewelryIterator(s.jewelryBox)
	return s.collect(iter)
}

// ListReverse 业务方法:反向遍历珠宝(完全扩展)
func (s *JewelryService) ListReverse() []*domain.Jewelry {
	iter := iterator.NewReverseJewelryIterator(s.jewelryBox)
	return s.collect(iter)
}

// collect 统一遍历收敛(单一职责:遍历收集)
func (s *JewelryService) collect(iter iterator.Iterator) []*domain.Jewelry {
	var list []*domain.Jewelry
	for iter.HasNext() {
		list = append(list, iter.Next())
	}
	return list
}

// -------------------------- 新增扩展方法 --------------------------

// ListByPrice 价格区间筛选
func (s *JewelryService) ListByPrice(min, max float64) []*domain.Jewelry {
	iter := iterator.NewPriceIterator(s.jewelryBox, min, max)
	return s.collect(iter)
}

// ListByBrand 按品牌筛选
func (s *JewelryService) ListByBrand(brand string) []*domain.Jewelry {
	iter := iterator.NewBrandIterator(s.jewelryBox, brand)
	return s.collect(iter)
}

// ListByPage 分页查询
func (s *JewelryService) ListByPage(pageNum, pageSize int) []*domain.Jewelry {
	iter := iterator.NewPageIterator(s.jewelryBox, pageNum, pageSize)
	return s.collect(iter)
}

// 材质
func (s *JewelryService) ListByMaterial(material string) []*domain.Jewelry {
	return s.collect(iterator.NewMaterialIterator(s.jewelryBox, material))
}

// 排序
func (s *JewelryService) ListSortByPrice(asc bool) []*domain.Jewelry {
	if asc {
		return s.collect(iterator.NewSortIterator(s.jewelryBox, iterator.SortAsc))
	}
	return s.collect(iterator.NewSortIterator(s.jewelryBox, iterator.SortDesc))
}

// 多条件组合
func (s *JewelryService) ListByComposite(filter iterator.CompositeFilter) []*domain.Jewelry {
	return s.collect(iterator.NewCompositeIterator(s.jewelryBox, filter))
}

// 并发安全遍历
func (s *JewelryService) ListConcurrentSafe() []*domain.Jewelry {
	return s.collect(iterator.NewConcurrentIterator(s.jewelryBox))
}
/*
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Iterator Pattern 迭代器模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : goLang 2024.3.6 go 26.2
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/4/21 22:06
# User      :  geovindu
# Product   : GoLand
# Project   : godesginpattern
# File      : formatter.go
*/
package utils

import (
	"encoding/json"
	"fmt"
	"godesginpattern/iterator/domain"
)

// PrintTable 控制台表格格式化输出
func PrintTable(list []*domain.Jewelry) {
	fmt.Println("----------------------------------------------------------------------")
	fmt.Printf("%-3s %-8s %-10s %-15s %-10s\n", "ID", "名称", "品牌", "材质", "价格")
	fmt.Println("----------------------------------------------------------------------")
	for _, v := range list {
		fmt.Printf("%-3d %-8s %-10s %-15s %-10.0f\n",
			v.ID, v.Name, v.Brand, v.Material, v.Price)
	}
	fmt.Println("----------------------------------------------------------------------")
}

// ToJSON 转为 JSON 字符串(API 输出)
func ToJSON(v interface{}) string {
	bytes, err := json.MarshalIndent(v, "", "  ")
	if err != nil {
		return "{}"
	}
	return string(bytes)
}

调用:

/*
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : goLang 2024.3.6 go 26.2
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/4/21 21:57
# User      :  geovindu
# Product   : GoLand
# Project   : godesginpattern
# File      : iteratorbll.go

iterator/
├── go.mod                  // 项目模块
├── main.go                 // 程序入口(应用层)
├── domain/                 // 领域模型层(核心实体)
│   └── jewelry.go          // 珠宝实体
├── iterator/               // 迭代器模式核心层(接口 + 实现)
│   ├── iterator.go         // 迭代器接口定义
│   ├── jewelry_iterator.go // 正向迭代器实现
│   └── reverse_iterator.go // 反向迭代器实现(扩展)
│   ├── price_iterator.go  # 新增 ✅
│   ├── brand_iterator.go  # 新增 ✅
│   └── page_iterator.go   # 新增 ✅
│   ├── material_iterator.go    # 新增:材质筛选
│   ├── sort_iterator.go        # 新增:价格排序
│   ├── composite_iterator.go   # 新增:多条件组合
│   └── concurrent_iterator.go  # 新增:并发安全
├── collection/             // 集合容器层
│   ├── collection.go       // 集合接口
│   └── jewelry_box.go      // 珠宝盒集合实现
└── service/                // 业务服务层(封装迭代逻辑)
│	└── jewelry_service.go  // 珠宝业务服务
└── utils/

	└── formatter.go            # 新增:统一格式化输出
*/
package bll

import (
	"fmt"
	"godesginpattern/iterator/domain"
	"godesginpattern/iterator/iterator"
	"godesginpattern/iterator/service"
	"godesginpattern/iterator/utils"
)

func IteratorMain() {
	// 1. 初始化服务(依赖注入,可替换、可 mock)
	js := service.NewJewelryService()

	// 2. 模拟添加珠宝数据
	js.AddJewelry(&domain.Jewelry{
		ID: 1, Name: "钻石戒指", Material: "铂金+钻石", Price: 19999.99, Brand: "周大福",
	})
	js.AddJewelry(&domain.Jewelry{
		ID: 2, Name: "黄金项链", Material: "足金999", Price: 8888.88, Brand: "老凤祥",
	})
	js.AddJewelry(&domain.Jewelry{
		ID: 3, Name: "翡翠手镯", Material: "天然翡翠", Price: 15888.00, Brand: "七彩云南",
	})

	// 3. 正向遍历(业务层调用,完全不感知迭代器细节)
	fmt.Println("===== 正向遍历 =====")
	for _, item := range js.ListForward() {
		fmt.Printf("ID:%d | %s | %s | ¥%.2f | %s\n",
			item.ID, item.Name, item.Material, item.Price, item.Brand)
	}

	// 4. 反向遍历(扩展能力)
	fmt.Println("\n===== 反向遍历 =====")
	for _, item := range js.ListReverse() {
		fmt.Printf("ID:%d | %s | %s | ¥%.2f | %s\n",
			item.ID, item.Name, item.Material, item.Price, item.Brand)
	}

	// 5. 价格区间:8000 ~ 20000
	fmt.Println("\n=== 价格 8000-20000 ===")
	for _, v := range js.ListByPrice(8000, 20000) {
		fmt.Printf("%s %.0f\n", v.Name, v.Price)
	}

	// 6. 品牌:周大福
	fmt.Println("\n=== 品牌:周大福 ===")
	for _, v := range js.ListByBrand("周大福") {
		fmt.Println(v.Name)
	}

	// 7. 分页:第 1 页,每页 2 条
	fmt.Println("\n=== 分页第1页,每页2条 ===")
	for _, v := range js.ListByPage(1, 2) {
		fmt.Println(v.Name)
	}

	fmt.Println("\n=== 1. 正向遍历 ===")
	utils.PrintTable(js.ListForward())

	fmt.Println("\n=== 2. 反向遍历 ===")
	utils.PrintTable(js.ListReverse())

	fmt.Println("\n=== 3. 价格区间 8000-20000 ===")
	utils.PrintTable(js.ListByPrice(8000, 20000))

	fmt.Println("\n=== 4. 品牌:周大福 ===")
	utils.PrintTable(js.ListByBrand("周大福"))

	fmt.Println("\n=== 5. 材质:足金 ===")
	utils.PrintTable(js.ListByMaterial("足金"))

	fmt.Println("\n=== 6. 价格降序 ===")
	utils.PrintTable(js.ListSortByPrice(false))

	fmt.Println("\n=== 7. 分页:第1页,每页2条 ===")
	utils.PrintTable(js.ListByPage(1, 2))

	fmt.Println("\n=== 8. 材质:足金 ===")
	utils.PrintTable(js.ListByMaterial("足金"))

	fmt.Println("\n=== 9. 多条件组合:品牌=老凤祥 + 价格≥10000 ===")
	filter := iterator.CompositeFilter{
		Brand:    "老凤祥",
		MinPrice: 10000,
	}
	utils.PrintTable(js.ListByComposite(filter))

	fmt.Println("\n=== 10. 并发安全遍历 ===")
	utils.PrintTable(js.ListConcurrentSafe())

	fmt.Println("\n=== 11. API JSON 输出 ===")
	fmt.Println(utils.ToJSON(js.ListForward()))

}

输出:

image

哲学管理(学)人生, 文学艺术生活, 自动(计算机学)物理(学)工作, 生物(学)化学逆境, 历史(学)测绘(学)时间, 经济(学)数学金钱(理财), 心理(学)医学情绪, 诗词美容情感, 美学建筑(学)家园, 解构建构(分析)整合学习, 智商情商(IQ、EQ)运筹(学)生存.---Geovin Du(涂聚文)