Iterator Pattern

  • Make a Class Iterable
  • Use with For Each Loops
  • Act Like a Collection

Iterator

  • Class to Keep Track of Location
  • Typically Includes next Method
  • Defined Way To Find End
  • Other Methods May Be Included

Iterable Interface

class CrayonBox implements Iterable[Crayon]:
List[Crayon] contents
function addCrayon(Crayon c): contents.add(c)
function getIterator(): return contents.getIterator()
function get(int i): return contents[i]
function contains(Crayon c): return contents.contains(c)
function size(): return contents.size()

Using an Iterable

class Main:
function main(): CrayonBox box = CrayonBoxFactorySingleton.getInstance().getBox(16) //get iterator and print for Crayon c in box: print(c.color)

Iterator Pattern

  • Offload Most of Work to Underlying Collection
  • Implement Helpful Collection Methods
  • Don't Reinvent the Wheel

Template Method Pattern

  • Define Method Structure in Parent
  • Override Portions in Child
  • Same Basic Steps, Different Details

Parent Class

abstract class Recipe:
function bakeSomething(): gatherIngredients() combineIngredients() putInOven()
abstract function gatherIngredients() abstract function combineIngredients() abstract function putInOven()

Child Class

class Cake inherits Recipe:
function gatherIngredients(): getFlour() getSugar() getEggs() getButter()
function combineIngredients() creamEggsAndButter() addSugar() addFlour()
function putInOven() setOven(350) setTimer(30)