This work by Marco Torchiano is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.
This is an example of the iterative and incremental use of patterns and language idioms to improve an initial simple solution. This example was originally developed for the Object Oriented Programming course at Politecnico di Torino
The class RandomSequence
provides as basic feature the generation
of a sequence of random integer numbers that can be iterated upon.
The method next()
returns the next number in the sequence.
In addition the sequence can be regenerated using renew()
and the iteration can start again from the first element with restart()
.
Code: RandomSequence.java
Limitations:
- one iteration at a time can be perfomed
- custom code must be written (e.g. no for-each construct can be used)
Using the iterator pattern support in Java, an iterable version is generated.
The main class implements the Iterable
interface
(an abstract factory of iterators).
The factory method (iterator()
) returns a new RIterator
,
which implements the Iterator
interface.
RIterator
is a nested class
that contains an index (initialized to 0
) and a reference to the array cotaining the sequence
(initialized using the reference to the sequence object).
Code: IterRandomSequence.java
Limitations:
- there are two reference to the sequence array, one in the main sequence class and one in the iterator class,
- the initialization of the iterator needs a (avoidable)
this
argument.
Using the features of inner classes, i.e. the automatic linkage to the creator enclosing class instance, the code of the iterator class can be simplified
Code: InnerIterRandomSequence.java
Limitations:
- iterator class
RIterator
is used only once, though it has a name
The usage of an anonymous inner class allow defining the iterator class and instantiating it without the need to provide a name.
The resulting code is even more compact.
Code: AnonInnerIterRandomSequence.java
Limitations
- the return type of the
next()
method is anObject
, thus an explicit cast is required
The generic interfaces Iterable
and Iterator
can be parameterized with the actual (wrapper) type
of the elements of the sequence.