Iterator
When discussing the Composite design pattern in the previous chapter, we identified a sense of incompleteness. The Iterator pattern is precisely what’s needed to complement it. Thus, it’s time to reunite these akin yet distinct concepts. They are somewhat analogous to Arnold Schwarzenegger and Danny DeVito - distinct in nature but synergistic when paired.
In this chapter, for the sake of simplicity, we define a Trooper
as follows:
open class Trooper {
fun move(x: Int, y: Int) {
println("Moving to $x:$y")
}
}
Similarly, the Squad
is simplified in the following manner:
class Squad(private val units: List<Trooper>) : Trooper() {
constructor(vararg units: Trooper) : this(units.toList())
}
This method ensures that our examples remain clear and succinct.
Now, recall from the previous chapter that a squad can consist of individual troopers or other squads. Let’s proceed to create such a squad:
...