zoukankan      html  css  js  c++  java
  • GoLang设计模式09

    迭代器模式是一种行为型模式。在这种模式中,集合结构会提供一个迭代器。通过这个迭代器可以顺序遍历集合中的每个元素而不需要暴露其具体的实现。

    下面是迭代器模式的一些具体实现:

    • Iterator 接口: 这个接口会定义一些基础的操作函数,如hasNext()getNext()等。通过名称就可以看出,这些方法可以帮助我们执行遍历集合、重启迭代等操作。
    • Collection 接口: 这个接口代表了要被遍历的集合。在这个接口里定义了一个createIterator方法,该方法会返回一个Iterator的实例。
    • Concrete Iterator: Iterator接口的具体实现类。
    • Concrete Collection: Collection接口的具体实现类。

    在golang当前的版本(1.16或更早)中是没有泛型的,所以一些特殊情况下还是需要会用到迭代器模式。

    来看下类图:

    下面是示例代码:

    iterator.go:

    type iterator interface {
    	hasNext() bool
    	getNext() *user
    }
    

    collection.go:

    type collection interface {
    	createIterator() iterator
    }
    

    user.go:

    type user struct {
    	name string
    	age  int
    }
    

    userIterator.go:

    type userIterator struct {
    	index int
    	users []*user
    }
    
    func (u *userIterator) hasNext() bool {
    	if u.index < len(u.users) {
    		return true
    	}
    	return false
    }
    
    func (u *userIterator) getNext() *user {
    	if u.hasNext() {
    		user := u.users[u.index]
    		u.index++
    		return user
    	}
    	return nil
    }
    

    userCollection.go:

    type userCollection struct {
    	users []*user
    }
    
    func (u *userCollection) createIterator() iterator {
    	return &userIterator{
    		users: u.users,
    	}
    }
    

    main.go:

    func main() {
    	user1 := &user{
    		name: "a",
    		age:  30,
    	}
    	user2 := &user{
    		name: "b",
    		age:  20,
    	}
    	userCollection := &userCollection{
    		users: []*user{user1, user2},
    	}
    	iterator := userCollection.createIterator()
    	for iterator.hasNext() {
    		user := iterator.getNext()
    		fmt.Printf("User is %+v
    ", user)
    	}
    }
    

    输出内容:

    User is &{name:a age:30}
    User is &{name:b age:20}
    

    代码已上传至GitHub: github / zhyea / iterator-design-pattern

    END!

     


    仅是学习笔记,难免出错,望不吝指点
  • 相关阅读:
    NBUT 1120 Reimu's Teleport (线段树)
    NBUT 1119 Patchouli's Books (STL应用)
    NBUT 1118 Marisa's Affair (排序统计,水)
    NBUT 1117 Kotiya's Incantation(字符输入处理)
    NBUT 1115 Cirno's Trick (水)
    NBUT 1114 Alice's Puppets(排序统计,水)
    188 Best Time to Buy and Sell Stock IV 买卖股票的最佳时机 IV
    187 Repeated DNA Sequences 重复的DNA序列
    179 Largest Number 把数组排成最大的数
    174 Dungeon Game 地下城游戏
  • 原文地址:https://www.cnblogs.com/amunote/p/15362908.html
Copyright © 2011-2022 走看看