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!

     


    仅是学习笔记,难免出错,望不吝指点
  • 相关阅读:
    函数二 10
    函数初识 09
    文件操作 08
    数据类型的补充 day07
    小数据池 深浅copy 集合
    python Mysql 多条件查询
    ElasticSearch Python 基本操作
    用PyInstaller把Python代码打包成单个独立的exe可执行文件
    python 编译EXE文件
    Git 创建新分支检查分支
  • 原文地址:https://www.cnblogs.com/amunote/p/15362908.html
Copyright © 2011-2022 走看看