JustNote
  • Introduction
  • DesignPattern
    • 七大原则
      • 开闭原则(OCP)
      • 依赖倒置原则(DIP)
      • 单一职责原则(SRP)
      • 接口隔离原则(ISP)
      • 迪米特法则(LoD)
      • 里氏代换原则(LSP)
      • 合成复用原则(CRP)
    • 创建型模式
      • 简单工厂模式
      • 工厂方法模式
      • 抽象工厂模式
      • 建造者模式
      • 单例模式
      • 原型模式
    • 结构型模式
      • 外观模式
      • 装饰模式
      • 适配器模式
      • 享元模式
      • 组合模式
      • 桥接模式
      • 代理模式
    • 行为型模式
      • 模板方法模式
      • 迭代器模式
      • 策略模式
      • 解释器模式
      • 观察者模式
      • 备忘录模式
      • 命令模式
      • 中介者模式
      • 责任链模式
      • 访问者模式
      • 状态模式
  • Java
    • Java Core
      • JVM 如何加载类
      • JVM 垃圾回收
      • JVM G1GC
      • JVM G1GC Q&A
      • JVM 与 Hbase
      • JVM ZGC Overview
      • JVM ZGC 内存管理
      • JVM ZGC 线程
      • JVM ZGC 垃圾回收
      • JVM ZGC 日志分析
      • JVM ZGC 参数调优
    • checkstyle
  • Golang
    • 源码阅读
      • Goroutines
      • Channel
    • gRPC
      • 1、快速开始
      • 2、什么是gRPC
      • 3、gRPC概念梳理
      • 4、基于Golang的gRPC入门
      • 5、gRPC组件ProtocolBuffers介绍
      • 6、gRPC组件Http 2.0
      • 7、错误处理和Debug
      • 8、gRPC身份验证
      • 9、服务注册与发现
      • 10、gRPC与gRPC Gateway
      • 11、gRPC与分布式链路追踪
  • Scala
    • 数据结构与算法
      • 数组
      • 队列
    • 函数式编程
      • 高阶函数
      • 偏函数
    • Immutable Collection
      • List
    • Mutable Collection
      • Array
    • 常见函数操作
      • A
        • aggregate
        • andThen
        • appended
        • appendedAll
      • C
        • chain
        • collect
        • collectFirst
        • combinations
        • compose
        • concat
        • cond
        • condOpt
        • const
        • contains
        • containsSlice
        • copyToArray
        • corresponds
        • count
        • curried
      • D
        • diff
        • distinct
        • distinctBy
        • drop
        • dropRight
        • dropWhile
      • E
        • empty(PartialFunction)
        • empty(collections)
        • endsWith
        • exists
      • F
        • fill
        • filter
        • filterKeys
        • filterNot
        • find
        • findLast
        • flatMap
        • flatten
        • fold
        • foldLeft
        • foldRight
        • forall
        • foreach
        • fromFunction
      • G
        • getOrElse (Map)
        • getOrElse (Option)
        • groupBy
        • groupMap
        • groupMapReduce
        • grouped
      • H
        • head
        • headOption
      • I
        • indexOf
        • indexOfSlice
        • indexWhere
        • indices
        • init
        • inits
        • intersect
        • isDefinedAt (Map)
        • isDefinedAt (Seq)
        • isEmpty
        • isTraversableAgain
      • K
        • keys
      • L
        • last
        • lastIndexOf
        • lastIndexOfSlice
        • lastIndexWhere
        • lastOption
        • length
        • lift
      • M
        • map
        • mapConserve
        • mapValues
        • max
        • maxBy
        • maxByOption
        • maxOption
        • min
        • minBy
        • minByOption
        • minOption
        • mkString
      • N
        • nonEmpty
      • O
        • orElse
      • P
        • padTo
        • par
        • partition
        • partitionMap
        • patch
        • permutations
        • prefixLength
        • prepended
        • prependedAll
        • product
      • R
        • range
        • reduce
        • reduceLeft
        • reduceLeftOption
        • reduceOption
        • reduceRight
        • reduceRightOption
        • reverse
        • reverseIterator
        • reverseMap
        • runWith
      • S
        • sameElements
        • scan
        • scanLeft
        • scanRight
        • search
        • segmentLength
        • size
        • slice
        • sliding
        • sortBy
        • sortWith
        • sorted
        • span
        • splitAt
        • startsWith
        • sum
      • T
        • tabulate
        • tail
        • tails
        • take
        • takeRight
        • takeWhile
        • transpose
        • tupled
      • U
        • unfold
        • union
        • unlift
        • untupled
        • unzip
        • unzip3
        • updated
      • V
        • values
        • view
      • W
        • withFilter
        • withDefault
        • withDefaultValue
      • Z
        • zip
        • zipAll
        • zipWithIndex
      • map
      • flatmap
      • filter
      • reduceLeft
      • foldLeft
    • Futures
      • Method with future as return type
      • Non blocking future result
      • Chain futures using flatMap
      • Chain futures using for comprehension
      • Future Option with for comprehension
      • Future Option with map
      • Composing Futures
      • Future Sequence
      • Future Traverse
      • Future foldLeft
      • Future reduceLeft
      • Future firstCompletedOf
      • Future zip
      • Future zipWith
      • Future andThen
      • Future configure threadpool
      • Future recover
      • Future recoverWith
      • Future fallbackTo
      • Future promise
    • Akka
  • Algorithm
  • Docker
  • Kubernetes
    • 二进制安装kubernetes
      • 00.从零开始
  • Architecture
    • Infrastructure
      • Opentracing
      • Jaeger && ZipKin
      • SkyWalking
      • Consul
      • Envoy
      • Service Mesh
      • Service Mesh: Istio 详解
      • Service Mesh: 基于 Istio 的落地实践(一)
    • CAS
      • CAS Server
      • CAS Service Management
      • CAS 集成LDAP
      • CAS 集成gitlab
      • CAS SSO & SLO
      • CAS Gitbook
    • xCAT
  • Netty
  • DDD
  • Reactive Programming
    • Reactor
      • Publisher
      • Subscriber
      • Subscription
      • Processor
    • WebFlux
  • Gitlab
    • Git Hook
  • CICD
    • Jenkins
      • Kubectl
Powered by GitBook
On this page
  • 适用场景
  • 优点
  • 缺点
  • Golang Demo
  • Java Demo
  • UML
  • 补充另一个版本的Java/Scala Demo 以及源码解析
  • Java Demo_
  • Scala Demo
  • UML_
  • 源码解析

Was this helpful?

  1. DesignPattern
  2. 行为型模式

迭代器模式

迭代器模式(Iterator Pattern): 提供一种方法,顺序访问一个集合对象中的各个元素,而又不暴露该对象的内部表示。

适用场景

  • 访问一个集合对象的内容,而无需暴露它的内部表示。

  • 为遍历不同的集合结构提供了一个统一的接口。

优点

  • 分离了集合对象的遍历行为

缺点

  • 类的个数成对增加,新增一个集合类,就需要相对应地增加一个迭代器类

迭代器模式在实际使用过程中是经常使用的一种设计模式,但是在实际编程过程中,很少有我们自己去实现一个迭代器,因为编程语言一般就给我们提供了相应集合类的迭代器。

Golang Demo

下面的示例并不能完全地表示迭代模式,建议参考java版示例。因为没有add和remove方法。实际使用中,我们并不需要亲自来实现,因为了解就可以。

package iterator

type Student struct {
    name string
}

type Iters []Student

func (i Iters) Iterator() *Iterator {

    return &Iterator{
        data:  i,
        index: 0,
    }

}

type Iterator struct {
    data  Iters
    index int
}

func (i *Iterator) HasNext() bool {
    return i.index < len(i.data)
}

func (i *Iterator) Next() (v Student) {
    v = i.data[i.index]
    i.index++
    return v
}
package iterator

import (
    "fmt"
    "testing"
)

func Test(t *testing.T) {
    iters := Iters{
        Student{name: "hello"},
        Student{name: "world"},
        Student{name: "!"},
    }

    for it := iters.Iterator(); it.HasNext(); {
        fmt.Println(it.Next())
    }
}

Java Demo

package tech.selinux.design.pattern.behavioral.iterator;

public class Student {
  private String name;

  public Student(String name) {
    this.name = name;
  }

  public String getName() {
    return name;
  }
}
package tech.selinux.design.pattern.behavioral.iterator;

public interface StudentAggregate {

  void addStudent(Student student);

  void removeStudent(Student student);

  StudentIterator getStudentIterator();
}
package tech.selinux.design.pattern.behavioral.iterator;

import java.util.ArrayList;
import java.util.List;

public class StudentAggregateImpl implements StudentAggregate {

  private List studentList;

  public StudentAggregateImpl() {
    this.studentList = new ArrayList();
  }

  @Override
  public void addStudent(Student student) {
    studentList.add(student);
  }

  @Override
  public void removeStudent(Student student) {
    studentList.remove(student);
  }

  @Override
  public StudentIterator getStudentIterator() {
    return new StudentIteratorImpl(studentList);
  }
}
package tech.selinux.design.pattern.behavioral.iterator;

public interface StudentIterator {
  Student nextStudent();

  boolean isLastStudent();
}
package tech.selinux.design.pattern.behavioral.iterator;

import java.util.List;

public class StudentIteratorImpl implements StudentIterator {

  private List studentList;
  private int position;
  private Student student;

  public StudentIteratorImpl(List studentList) {
    this.studentList = studentList;
  }

  @Override
  public Student nextStudent() {
    System.out.println("result ,位置是: " + position);
    student = (Student) studentList.get(position);
    position++;
    return student;
  }

  @Override
  public boolean isLastStudent() {
    if (position < studentList.size()) {
      return false;
    }
    return true;
  }
}
package tech.selinux.design.pattern.behavioral.iterator;

public class Test {

  public static void main(String[] args) {
    Student student1 = new Student("Student 1");
    Student student2 = new Student("Student 2");
    Student student3 = new Student("Student 3");
    Student student4 = new Student("Student 4");
    Student student5 = new Student("Student 5");
    Student student6 = new Student("Student 6");

    StudentAggregate studentAggregate = new StudentAggregateImpl();

    studentAggregate.addStudent(student1);
    studentAggregate.addStudent(student2);
    studentAggregate.addStudent(student3);
    studentAggregate.addStudent(student4);
    studentAggregate.addStudent(student5);
    studentAggregate.addStudent(student6);

    System.out.println("-----Student list -----");
    printCourses(studentAggregate);

    studentAggregate.removeStudent(student4);
    studentAggregate.removeStudent(student5);

    System.out.println("-----Student list 2-----");
    printCourses(studentAggregate);
  }

  public static void printCourses(StudentAggregate studentAggregate) {
    StudentIterator studentIterator = studentAggregate.getStudentIterator();
    while (!studentIterator.isLastStudent()) {
      Student student = studentIterator.nextStudent();
      System.out.println(student.getName());
    }
  }
}

UML

补充另一个版本的Java/Scala Demo 以及源码解析

Java Demo_

Scala Demo

UML_

源码解析

Previous模板方法模式Next策略模式

Last updated 5 years ago

Was this helpful?

迭代器模式UML